如何获得angularjs一个自定义标签的属性值? [英] How to get attribute value of a custom tag in angularjs?
问题描述
我想创建一个自定义标记的使用angularJs。这个标签有一个名为的属性数据
。 数据
得到它看重这样的< skillviz数据={{user.info}}>< / skillviz>
。 user.info
是一个JSON对象。但是,当我尝试访问我的指令定义这个数据
属性,我得到未定义
。什么是做到这一点的正确方法?
I am trying to create a custom tag using angularJs. This tag has an attribute named data
. data
gets it value like this <skillviz data="{{user.info}}"></skillviz>
. user.info
is a JSON object. But when i try to access this data
attribute in my directive definition, I get undefined
. What is the correct way to do this ?
HTML code
<div id="info-box" ng-repeat="user in users | orderBy:orderProp">
<div id="skill-block">
<skillviz height="50" data="{{user.skills}}"></skillviz>
</div>
</div>
用户
是一个JSON类型的对象,在控制器中声明。所以基本上用户
将是一个列表(数组)
users
is a JSON type object, declared in the controller. So basically users
will be a list(array) of
{"first_name": "Tifanny",
"last_name": "Maxwell",
"skills": [
{"name": "Java", "score": 4.8, "color" : "red"},
{"name": "C++", "score": 4.0, "color" : "blue"},
]
},
services.js
angular.module('yott', []).directive('skillviz', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
element.html("<script>alert(" + attrs['data'] + ")</script>");
});
}
}
});
提示框弹出说的未定义
推荐答案
使用 $观察
来观察更改属性:
attrs.$observe('data', function(value) {
console.log('data has changed value to ' + value);
});
和 $设置
来改变值:
attrs.$set('data', 'new value');
另外,您可以通过/使用 @
(绑定一个本地范围内)将其链接到该指令范围,&安培;
(提供了一种方法来执行父范围的上下文中的前pression)或 =
(设置双向绑定) - 解释的here
Alternatively you can pass/link it into the directive scope using @
(bind a local scope), &
(provides a way to execute an expression in the context of the parent scope) or =
(set up bi-directional binding) – explained here
angular.module('yott', []).directive('skillviz', function () {
return {
restrict: 'E',
scope { data: "=data" },
link: function (scope, element, attrs) {
element.html("<script>alert(" +scope.data + ")</script>");
});
}
}
});
这篇关于如何获得angularjs一个自定义标签的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!