AngularJS:如何从子控制器更新指令作用域

AngularJS : How to update directive scope from child controllers

本文关键字:控制器 更新 指令 作用域 AngularJS      更新时间:2023-09-26

我有一个简单的父/子控制器设置如下:

<body ng-controller="ParentCtrl">
    <section my-directive></section>
    <div ng-controller="Child1Ctrl">
        <button ng-click="child1()">Click Child1</button>
    </div>
    <br>
    <div ng-controller="Child2Ctrl">
        <button ng-click="child2()">Click Child2</button>
    </div>
</body>

当我点击任何一个按钮时,从Child1Ctrl或Child2Ctrl,我希望my-directive内的范围被更新。

myDirective.js

app.directive('myDirective', function () {
    var slider = {
        initial : function() {
            slider.clear();
            $scope.slideHide = false;
            $scope.slideShow = false;
        },
        clear: function() {
            $scope.slideMessage = '';
            $scope.slideError = false;
            $scope.slideSuccess = false;
        },
        error: function(message) {
            $scope.slideShow = true;
            $scope.slideError = true;
            $scope.slideMessage = message;
        },
        success: function(message) {
            $scope.slideShow = true;
            $scope.slideSuccess = true;
            $scope.slideMessage = message;
        }
    }
    return {
       restrict: 'A',
       replace: true,
       transclude: true,
       template: '<section class="slide">' +
                '<div data-ng-class="{''slide-show'' : slideShow, ''slide-error'' : slideError, ''slide-success'' : slideSuccess, ''slide-hide'' : slideHide}">' +
                    '<p>{{ slideMessage }}</p>' +                           
                '</div>' +
            '</section>'
            }
        }
    );

在子控制器中调用:

app.controller('Child1Ctrl', function($scope) {
    $scope.child1 = function () {
        $scope.$parent.slider.initialise();
    }
});
app.controller('Child2Ctrl', function($scope) {
    $scope.child2 = function () {
        $scope.$parent.slider.success('Display some text');
    }
});

更新:

http://jsfiddle.net/6uub3jqx/1/

如果你点击第一组按钮,红/绿色带出现。

如果你点击child1/2控制器内的按钮,没有任何动作。


解决方案:

参见:http://jsfiddle.net/6uub3jqx/2/

实际上子节点应该发送:

$scope.successChild1 = function(msg) { 
    $scope.$emit('successCh1', 'Some data');
};

父母应该收到:

$scope.$on('successCh1', function (event, data) {
    $scope.$broadcast('success', data);
});

rootscope会是一个更好的选择吗?

看情况。你既可以使用Angular的事件,也可以使用(在我看来更好的方法)保留状态的服务,例如:

.factory('myOwnScope', function () {
    return {};
});
// include myOwnScope as dependency and share the information
// between controllers and directive by its properties
// (any Angular service is just a singleton)

有几种方法可以做到这一点。哪一种方法是最好的取决于你想要达到的目标。

一种可能是向你的指令中注入数据。那么你就不需要$parent变量了。

它会像这样(但不能保证它能工作,因为你没有一个活塞或类似的东西)

在你的html中:

<section my-directive mytext="myobject.mymessage"></section>

在你的控制器中:

$scope.myobject = { mymessage: 'hi there' };

在你的指令中:

return {
   restrict: 'A',
   scope: { mytext: '=' }
   template: '{{mytext}}'
}