AngularJS同一指令的两个实例互相更新

时间:2014-03-18 12:20:56

标签: angularjs angularjs-directive

就像标题所说我有两个相同指令的实例,在启动时都有相同的数据。当每个人都改变时,我如何让他们互相更新?

myApp.directive('locationSelector',function () {
    return {
        restrict: 'E',
        templateUrl: 'App/Common/templates/locationSelectorTemplate.html',
        scope: {
            someValue: '@val'
        },
        controller: function ($scope, locationsService) {
          // get the available locations from service
          $scope.locations = locationsService.getLocations();
          // select the first option as the default value for the ng-options
          $scope.location = $scope.locations[0];

          // do something when the other directive value changes
          // 
          //

        },
        link: function (scope,element,attrs) {

        }
    };
});

例如,假设它们都以值开头:{'a','b','c'} 现在假设用户在第一个指令上选择了'b',第二个指令应该更改为'c'。然后用户在第二个指令上选择了'a',现在第一个应该更改为'a'(此示例的更改逻辑并不重要)。

1 个答案:

答案 0 :(得分:2)

指令控制器是要走的路,它是它的确切用例,即指令之间的API。您需要做的是将指令控制器功能提取到其自己的容器指令中,并使用locationSelector指令require此容器指令来访问其控制器。

这是表单及其相关输入/ ngModel指令之类的指令进行通信的确切方式。每个输入指令都向父表单指令控制器注册,例如验证等。

已经有很多关于如何实现这一点的优秀示例,以下是一些带有源代码链接的示例:

angular-ui bootstrap Tabshttps://github.com/angular-ui/bootstrap/blob/master/src/tabs/tabs.js

<tabset vertical="true" type="navType">
  <tab heading="Vertical 1">Vertical content 1</tab>
  <tab heading="Vertical 2">Vertical content 2</tab>
</tabset>

在上面的示例中,tabset指令是带控制器的容器指令。

angular-ui bootstrap Accordianhttps://github.com/angular-ui/bootstrap/blob/master/src/accordion/accordion.js

Angular form指令:https://github.com/angular/angular.js/blob/master/src/ng/directive/form.js Angular input和ngModel指令:https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js