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;喜欢所有的工厂。然后你可以找到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/

相关文章:

javascript - JSON.parse()无法正常工作

angularjs - 如果{{user.userName}}为空,我可以在div中显示替代文本吗?

android - 制作我的 Ionic AngularJS 程序的 iOS 应用程序

python - .NET Core 2.0 和 Angular 初始应用程序构建失败 - 找不到 python 后跟 JavaScript 运行时错误

c - C变量覆盖值

javascript - 调用后的Vuejs axios变量分配

javascript - 使用 jQuery 将一个 DIV 的内容移动到另一个 DIV

c++ - 一种在C++中交换两个引用的方法

c - 将指向字符串数组的指针传递给 C 中的 toupper()

javascript - 使用 Express 和 Ember 启动 Web 应用程序