为Angular Directive添加多个'require'选项

时间:2014-05-06 13:39:09

标签: javascript angularjs angularjs-directive angularjs-scope angular-directive

通常在指令中,如果我想将范围传递给它,我会使用require: 'ngModel'。这很好用。但我现在正在创建一个指令,该指令创建5个不同的HTML元素,每个元素都有不同的ngModel从父级传递。需要作为属性传递的ngmodel是ngModel1, ngModel2, ngModel3, ngModel4, ngModel5。如何在指令内的require条件中添加多个选项?

我试过这些并且它不起作用:

require: ['ngModel1', 'ngModel2', 'ngModel3', 'ngModel4', 'ngModel5'],

require: {'ngModel1', 'ngModel2', 'ngModel3', 'ngModel4', 'ngModel5'},

require: 'ngModel1', 'ngModel2', 'ngModel3', 'ngModel4', 'ngModel5',

require: 'ngModel1, ngModel2, ngModel3, ngModel4, ngModel5'},

如何添加多个需求选项?

编辑:

HTML code:

<div get-vehicles-checkbox
            cars-ng-model="formData.cars"           
            bikes-ng-model="formData.bikes"         
            trucks-ng-model="formData.trucks"           
            van-ng-model="formData.van"         
            bus-ng-model="formData.bus"     
></div>

指令:

app.directive('getVehiclesCheckbox', function($compile) { 
  return {
    restrict: 'A',
    replace:true,
    // require: ?
    scope: {            
      carsNgModel: '=',
      bikesNgModel: '=',
      trucksNgModel: '=',
      vanNgModel: '=',
      busNgModel: '='
    },

    controller: 'SomeController',

    link: function(scope, element, attrs, carsNgModel, bikesNgModel, trucksNgModel, vanNgModel, busNgModel) {

      scope.carsNgModel = {},
        scope.bikesNgModel = {},
        scope.trucksNgModel = {},
        scope.vanNgModel = {},
        scope.busNgModel = {}

      var html = '<span ng-repeat="car in cars">' +
          '<input type="checkbox" ng-model="carsNgModel[car.code]"> {{ car.number }} {{ car.description }}' + 
          '</span>' +

          '<span ng-repeat="bike in bikes">' +
          '<input type="checkbox" ng-model="bikesNgModel[bike.code]"> {{ bike.number }} {{ bike.description }}' + 
          '</span>';

      //.... etc.. etc.....


      // COMPILE HTML
      //... .... ...

    }
  }
});

1 个答案:

答案 0 :(得分:29)

app.directive('myDirective', function() {
  return {
    restrict: "A",
    require:['^parentDirective', '^ngModel'], 
    link: function ($scope, $element, $attrs, controllersArr) {
      // parentDirective controller
      controllersArr[0].someMethodCall();

      // ngModel controller         
      controllersArr[1].$setViewValue(); 
    }
  }
});