AngularJS从其他控制器更新$scope

AngularJS update $scope from other controller

本文关键字:scope 更新 控制器 其他 AngularJS      更新时间:2023-09-26

我有以下问题:

在我的控制器中,我有这样的内容:

$scope.current = 0;

我有一些指令,它看起来像这样:

angular.module('myAPP')
    .directive('post', function() {
        return {
            restrict: 'EA',
            replace: true,
            scope: {
                post: '=',
                index: '='
            },
        link: function(scope) {
          //update the $scope.current here
        },
        templateUrl: 'components/blog/post.html'
    };
});

有人能告诉我什么是最好的方法来做到这一点,它可以更新$作用域内的链接函数?

谢谢!

您的指令有一个隔离的scope

要从指令中更改current,必须将其与指令作用域变量绑定,如下所示

这样的

<post index="current"></post>

js

link: function(scope) {
   scope.index=2;
},

您需要使用事件处理程序。它应该看起来像这样:

angular.module('myAPP')
    .directive('post', function() {
        return {
            restrict: 'EA',
            replace: true,
            scope: {
                post: '=',
                index: '='
            },
        link: function(scope) {
          $scope.on('my-event', function(value){
             $scope.current = value;
          });
          //update the $scope.current here
        },
        templateUrl: 'components/play/questions/simple-question.html'
    };
});

在你的控制器中,你将发送通知事件到你的指令:

$scope.emit('my-event', $scope.current);

如果你的指令位于控制器之外,那么你需要使用$rootScope来代替。