angularJS中父子指令之间的通信

时间:2014-11-21 00:28:04

标签: angularjs angularjs-directive

我创建了2个指令loginrankSelector。从下面的代码中可以看出,登录在rankSelector内部使用。但是,我不确定在这两个指令之间实现通信的正确方法是什么? rankSelectorlogin的父级,需要知道login指令何时发生某些更改。 ATM我使用rankSelector中的控制器,它具有passwordsMatch方法login当需要通知父指令有关更改时调用。代码如下:

                                                                    
    <script type="text/ng-template" id="rankSelector.html">

        <form name="rankings" novalidate>

            <div>

                <div login></div>

                <!-- if passwords match show this -->

                <input type="text" ng-model="someOtherField" name="someOtherField" ng-show="passwordsMatch" ng-hide="!passwordsMatch" />

            </div>

        </form>

    </script>

我的指示:

app.directive("login", [

    function(loginService) {
        return {
            templateUrl: "login.html",
            replace: true,
            require: "?^rankSelector",
            scope: true,
            link: function(scope, elem, attrs, ctrl) {
                scope.$watch("confirmPassword", function(newValue, oldValue) {

                    // also how in here I can check if scope.password is $valid without douing checks manually?
                    ctrl.passwordsMatch(scope.password && scope.password === scope.confirmPassword);
                });
            }
        };
    }
]);

app.directive("rankSelector", [

    function(rankingsService, $rootScope) {
        return {
            templateUrl: "rankSelector.html",
            replace: true,
            controller: ["$scope",
                function($scope) {
                    this.passwordsMatch = function(showConfirm) {
                        $scope.passwordsMatch = showConfirm;
                    }
                }
            ],
            scope: true,
            link: function(scope, elem, attrs) {
                scope.passwordsMatch = false;
            }
        };
    }
]);

不确定我是否在这里做正确的事情,因为login指令需要知道它将插入哪个控制器。我需要注意这种方法有什么明显的问题吗?

另外,如何在login调用中$watch指令内部进行检查以查看字段是否为$valid等?

1 个答案:

答案 0 :(得分:0)

在范围链中传递信息的最佳方法是使用事件。 在您的情况下,当您希望父指令作出反应时,您的登录指令会发出事件。

scope.$emit('somethingChanged', anyData);

然后在rankSelector中你会听取事件并对它做出反应

scope.$on('somethingChanged', function($event, anyData) {
    // react to the change
})