javascript - 将服务对象属性的指针/引用添加到 $scope 变量

标签 javascript angularjs pointers

如何将对象属性(也是对象)的指针/引用添加到 Angular $scope?

考虑以下代码:

videosModule.factory('VideoManager', ['YtVideos', function(YtVideos){ 
    return {
        videos: [{}, {}, {}],
        currentVideo: {},
        counter: 0,

        setCurrentVideo: function(){
            this.currentVideo = this.videos[this.counter];
        }
    };

}]);

Controller :

videosModule.controller('SelectVideoCtrl', ['VideoManager', '$scope', function(VideoManager, $scope){

    $scope.currentVideo = VideoManager.currentVideo;

    $scope.videomanager = VideoManager;

}]);

现在我希望 Controller 中的第一行指向属性 currentVideo,以便在服务中更改该属性时,它将更新到 $scope。

这不起作用,但是当我引用整个服务(第二行)并使用 {{ videomanager.currentVideo }} 时它确实起作用。

有人能解释一下吗? 谢谢。

最佳答案

$scope.currentVideo = VideoManager.currentVideo; 是你值(value)的表现。这意味着它永远不会改变。如果进行此更改,您将获得第二种语法: $scope.videomanager = VideoManager; ,类似于 all 工厂。然后你就可以找到currentVideo

但是,如果您想要类似于第一种语法的内容(并避免使用墙工厂对象),您可以使用函数。 setter/getter 就可以了:

videosModule.factory('VideoManager', ['YtVideos', function(YtVideos){ 
  return {
    videos: [{}, {}, {}],
    currentVideo: {},
    counter: 0,

    setCurrentVideo: function(){
        this.currentVideo = this.videos[this.counter];
    },

    getCurrentVideo : function(){
        return this.currentVideo;
    }

  };
}]);

然后你的 Controller 必须链接这个 getter。

videosModule.controller('SelectVideoCtrl', ['VideoManager', '$scope', function(VideoManager, $scope){
    $scope.currentVideo = VideoManager.getCurrentVideo;
    $scope.videomanager = VideoManager;
}]);

请注意, Controller 中没有 ()。如果您希望刷新该值,则必须将它们放入您的 DOM 中。这里只是功能链接。在你的 HTML 上,它会是这样的:

{{currentVideo()}}

关于javascript - 将服务对象属性的指针/引用添加到 $scope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31788489/

相关文章:

javascript - Angular ng-submit 只允许作用域内的函数

javascript - 使用 javascript 从 WordPress 页面读取 HTML

c++ - 如何将指针重置为特定的数组位置?

javascript - Tapable.plugin 已弃用。改用 `.hooks` 上的新 API

javascript - 在浏览器中调用 javascript 函数时指定的强制转换无效

javascript - 使用数据属性将鼠标悬停在链接上时更改(和淡入/淡出)图像

C |指针|分段故障

javascript - PDF 动态内容 - 这可能吗?

javascript - 如何使用过滤器删除数组中的对象? AngularJS

c - 运行时内存