2014-11-21 54 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 
})