2014-11-21 23 views
0

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

<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等?

回答

0

向范围链传递信息的最佳方式是使用事件。 在你的情况下,如果你想要父指令作出反应,你会让你的登录指令发出一个事件。

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

然后在rankSelector你会监听的事件和反应,因此

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