How do I pass multiple attributes into an Angular.js attribute directive?

后端 未结 5 1007
长发绾君心
长发绾君心 2020-11-30 18:57

I have an attribute directive restricted as follows:

 restrict: \"A\"

I need to pass in two attributes; a number and a function/callback, a

5条回答
  •  伪装坚强ぢ
    2020-11-30 19:40

    The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.

    Template:

    Directive:

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

    fiddle

    If the value of attribute example-number will be hard-coded, I suggest using $eval once, and storing the value. Variable num will have the correct type (a number).

提交回复
热议问题