gpt4 book ai didi

AngularJs 指令 - 如何从指令中获取属性值

转载 作者:行者123 更新时间:2023-12-04 11:09:26 27 4
gpt4 key购买 nike

知道如何从指令内部访问属性值吗?

    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代码是:
<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>

谢谢

最佳答案

使用 $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 to undefined. -- directives doc


return function(scope, element, attrs) {
attrs.$observe('key', function(value) {
console.log('key=', value);
});
}

正如@FMM 在评论中提到的, data Angular 在规范化属性名称时将其剥离,因此使用 key以上,而不是 dataKey .

关于AngularJs 指令 - 如何从指令中获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16300258/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com