如何将指向对象属性(也是对象)的指针/引用添加到 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;
喜欢所有的工厂。然后你可以找到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 将不得不链接这个 setter/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/