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

Und*_*ion 114 javascript parameters attributes directive angularjs

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

 restrict: "A"
Run Code Online (Sandbox Code Playgroud)

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

如果指令是一个元素指令,那么"E"我可以限制:

<example-directive example-number="99" example-function="exampleCallback()">
Run Code Online (Sandbox Code Playgroud)

但是,由于我不会进入的原因,我需要将指令作为属性指令.

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

Mar*_*cok 200

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

模板:

<div example-directive example-number="99" example-function="exampleCallback()"></div>
Run Code Online (Sandbox Code Playgroud)

指示:

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()
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

fiddle

如果属性的值example-number将被硬编码,我建议使用$eval一次,并存储该值.变量num将具有正确的类型(数字).


Jon*_*wny 19

您可以使用与element指令完全相同的方式执行此操作.你将把它们放在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);
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

用作:

<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>
Run Code Online (Sandbox Code Playgroud)


The*_*ris 9

您可以将对象作为属性传递,并将其读入指令,如下所示:

<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);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)