如何将多个属性传递给 Angular.js 属性指令? [英] How do I pass multiple attributes into an Angular.js attribute directive?

查看:35
本文介绍了如何将多个属性传递给 Angular.js 属性指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an attribute directive restricted as follows:

 restrict: "A"

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

I need to pass in two attributes; a number and a function/callback, accessing them within the directive using the attrs object.

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

If the directive was an element directive, restricted with "E" I could to this:

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

但是,由于我不会深入讨论的原因,我需要将指令设为属性指令.

However, for reasons I won't go into I need the directive to be an attribute directive.

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

推荐答案

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

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

模板:

<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 的值是硬编码的,我建议使用 $eval 一次,并存储值.变量 num 将具有正确的类型(数字).

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

这篇关于如何将多个属性传递给 Angular.js 属性指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆