json 如何在angularjs中获取自定义标签的属性值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16879212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get attribute value of a custom tag in angularjs?
提问by batman
I am trying to create a custom tagusing angularJs. This tag has an attribute named data. datagets it value like this <skillviz data="{{user.info}}"></skillviz>. user.infois a JSON object. But when i try to access this dataattribute in my directive definition, I get undefined. What is the correct way to do this ?
我正在尝试使用 angularJs创建自定义标签。这个标签有一个名为 的属性data。data像这样得到它的价值<skillviz data="{{user.info}}"></skillviz>。user.info是一个 JSON 对象。但是当我尝试data在我的指令定义中访问这个属性时,我得到undefined. 这样做的正确方法是什么?
html code
html代码
<div id="info-box" ng-repeat="user in users | orderBy:orderProp">
<div id="skill-block">
<skillviz height="50" data="{{user.skills}}"></skillviz>
</div>
</div>
usersis a JSON type object, declared in the controller. So basically userswill be a list(array) of
users是一个 JSON 类型的对象,在控制器中声明。所以基本上users将是一个列表(数组)
{"first_name": "Tifanny",
"last_name": "Maxwell",
"skills": [
{"name": "Java", "score": 4.8, "color" : "red"},
{"name": "C++", "score": 4.0, "color" : "blue"},
]
},
services.js
服务.js
angular.module('yott', []).directive('skillviz', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
element.html("<script>alert(" + attrs['data'] + ")</script>");
});
}
}
});
alert box pops up saying undefined
弹出警告框说未定义
采纳答案by winkerVSbecks
Use $observeto observe changes to the attribute:
使用$observe观察更改属性:
attrs.$observe('data', function(value) {
console.log('data has changed value to ' + value);
});
And $setto change value:
并$set改变价值:
attrs.$set('data', 'new value');
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
或者,您可以使用@(绑定本地范围),&(提供一种在父范围的上下文中执行表达式的方法)或=(设置双向绑定)将其传递/链接到指令范围– 解释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>");
});
}
}
});
回答by Juampy NR
Let's say you have the following markup:
假设您有以下标记:
<div ng-controller="MyController" data-id="someCustomValue">
</div>
Now in your controller you can do the following to access data-id:
现在在您的控制器中,您可以执行以下操作来访问data-id:
app.controller('MyController', function ($scope, $attrs) {
console.log($attrs.id); // Prints 'someCustomValue'
});

