如何将多个属性传递给一个Angular.js属性指令?

我有一个属性指令限制如下:

restrict: "A" 

我需要传递两个属性; 一个数字和一个函数/callback,使用attrs对象在指令中访问它们。

如果指令是一个元素指令,用"E"限制,我可以这样做:

 <example-directive example-number="99" example-function="exampleCallback()"> 

但是,由于我不会去的原因,我需要指令是一个属性指令。

如何将多个属性传递给属性指令?

指令可以访问在同一元素上定义的任何属性,即使指令本身不是元素。

模板:

 <div example-directive example-number="99" example-function="exampleCallback()"></div> 

指示:

 app.directive('exampleDirective ', function () { return { restrict: 'A', // 'A' is the default, so you could remove this line scope: { callback : '&exampleFunction', }, link: function (scope, element, attrs) { var num = scope.$eval(attrs.exampleNumber); console.log('number=',num); scope.callback(); // calls exampleCallback() } }; }); 

小提琴

如果属性example-number的值将被硬编码,我build议使用$eval一次,并存储该值。 variablesnum将具有正确的types(一个数字)。

你可以像使用元素指令一样来完成。 你会把它们放在attrs对象中,我的示例通过隔离范围将它们双向绑定,但这不是必需的。 如果您使用的是独立作用域,则可以使用scope.$eval(attrs.sample)或简单的scope.sample来访问这些属性,但根据您的情况,它们可能不会在链接上定义。

 app.directive('sample', function () { return { restrict: 'A', scope: { 'sample' : '=', 'another' : '=' }, link: function (scope, element, attrs) { console.log(attrs); scope.$watch('sample', function (newVal) { console.log('sample', newVal); }); scope.$watch('another', function (newVal) { console.log('another', newVal); }); } }; }); 

用作:

 <input type="text" ng-model="name" placeholder="Enter a name here"> <input type="text" ng-model="something" placeholder="Enter something here"> <div sample="name" another="something"></div> 

你可以传递一个对象作为属性,并像下面这样读入指令:

 <div my-directive="{id:123,name:'teo',salary:1000,color:red}"></div> app.directive('myDirective', function () { return { link: function (scope, element, attrs) { //convert the attributes to object and get its properties var attributes = scope.$eval(attrs.myDirective); console.log('id:'+attributes.id); console.log('id:'+attributes.name); } }; }); 

这工作对我来说,我认为更符合HTML5。 你应该改变你的HTML使用“数据”的前缀

 <div data-example-directive data-number="99"></div> 

在指令中读取variables的值:

 scope: { number : "=", .... }, 

如果你从另一个指令“需要”exampleDirective +你的逻辑是在“exampleDirective”控制器(比如说'exampleCtrl'):

 app.directive('exampleDirective', function () { return { restrict: 'A', scope: false, bindToController: { myCallback: '&exampleFunction' }, controller: 'exampleCtrl', controllerAs: 'vm' }; }); app.controller('exampleCtrl', function () { var vm = this; vm.myCallback(); });