小编典典

为 Angular 指令添加多个“要求”选项

all

通常在指令中,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'},

如何添加多个 require 选项?

编辑:

HTML 代码:

<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
      //... .... ...

    }
  }
});

阅读 106

收藏
2022-05-16

共1个答案

小编典典

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(); 
    }
  }
});
2022-05-16