AngularJs指令 – 如何从内部指令获取属性值

前端之家收集整理的这篇文章主要介绍了AngularJs指令 – 如何从内部指令获取属性值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
任何想法如何从指令内部访问属性值?
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>

谢谢

使用$观察:

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. — 07000

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

在注释中提到的@FMM中,当正规化属性名称时,Angular会剥离数据,因此使用上面的键而不是dataKey。

猜你在找的Angularjs相关文章