AngularJs指令 - 如何从指令中获取属性值 [英] AngularJs directives - how to get attributes values from within directive

查看:100
本文介绍了AngularJs指令 - 如何从指令中获取属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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 to undefined. -- 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 of key above, rather than dataKey.

这篇关于AngularJs指令 - 如何从指令中获取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆