Javascript AngularJS从其他控制器更新$scope

Javascript AngularJS从其他控制器更新$scope,javascript,angularjs,Javascript,Angularjs,我有以下问题: 在我的控制器中,我有如下内容: $scope.current = 0; 我有一些指示,看起来像这样: angular.module('myAPP') .directive('post', function() { return { restrict: 'EA', replace: true, scope: { post: '=',

我有以下问题:

在我的控制器中,我有如下内容:

$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'
    };
});
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'
    };
});
有人能告诉我做这件事的最好方法是什么吗?有可能在link函数中更新$scope吗

谢谢

您需要使用。应该是这样的:

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'
    };
});
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

您的指令具有隔离
范围

要从指令更改当前的
,必须将其与指令范围变量绑定,如下所示

像这样

html

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

我很高兴能帮上忙:)这是正确的方法。有关此双向
=
绑定的工作原理,请参阅下面的范围部分