AngularJs指令 - 如何从指令中获取属性值 [英] AngularJs directives - how to get attributes values from within directive
问题描述
不知道如何从指令内部访问属性的值?
angular.module('portal.directives',[])
.directive('languageFlag',['$ routeParams',函数(PARAMS){
返回功能(范围,元素,ATTRS){
的console.log(ATTRS [数据键]); //返回undefined
的console.log(element.attr(数据键')); //返回{{数据键}}
angular.element(元素)的.css('边界','1px的红色实');
};
}]);
HTML code是:
< UL>
<李NG重复=LNG的标志>
<一类=lngFlag {{flag.Key}}数据键={{flag.Key}}数据ID ={{lng.Id}}NG点击=changeLangHash({' LNG':lng.Id})语言旗>< / A>
< /李>
< / UL>
感谢
使用 $观察
:
的观察插值属性的:使用
$观察
来观察包含插补属性值的变化(如SRC = {{栏}}
)。这不仅是非常有效的,但它也可以轻松地获得实际价值的唯一方式,因为在链接阶段插值尚未评估,因此该值时,设置为未定义
。 - 指令DOC
块引用>返回功能(范围,元素,ATTRS){
ATTRS。观察$('键',功能(价值){
的console.log(键=',值);
});
}由于在评论中提到@FMM,
数据
是由角剥离时,它标准化的属性名称,因此,使用键
上面,而不是dataKey
。Any idea how to access attributes values from inside the directive?
angular.module('portal.directives', []) .directive('languageFlag', ['$routeParams', function(params) { return function(scope, element, attrs) { console.log(attrs["data-key"]); // returns undefined console.log(element.attr('data-key')); // returns {{data-key}} angular.element(element).css('border', '1px solid red'); }; }]);
Html code is:
<ul> <li ng-repeat="lng in flags"> <a class="lngFlag {{flag.Key}}" data-key="{{flag.Key}}" data-id="{{lng.Id}}" ng-click="changeLangHash({'lng':lng.Id })" language-flag></a> </li> </ul>
Thanks
解决方案Use
$observe
:Observing interpolated attributes: Use
$observe
to observe the value changes of attributes that contain interpolation (e.g.src="{{bar}}"
). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set toundefined
. -- directives doc
return function(scope, element, attrs) { attrs.$observe('key', function(value) { console.log('key=', value); }); }
As @FMM mentioned in a comment,
data
is stripped by Angular when it normalizes the attribute name, hence the use ofkey
above, rather thandataKey
.这篇关于AngularJs指令 - 如何从指令中获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!