如何将对象属性(也是对象)的指针/引用添加到 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/