AngularJs无法读取动态设置属性

AngularJs无法读取动态设置属性

本文介绍了AngularJs无法读取动态设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够创建,到底从属性的元素创建HighCharts图的angularjs指令。我有一个指导工作,但任何动态设置属性返回undefined。最后,我希望所有的元素的属性被发送到一个$ http请求的PARAMS。

我已经使用$观察方法尝试和它似乎并没有工作,还我想的属性是什么,而不是predefined。

看到这个小提琴:并低于code指令:

  myApp.directive(示例,函数(){
    返回{
        限制:'A',
        链接:功能(范围,元素,ATTRS){
            的console.log('LOG1:',attrs.exampleId);
            ATTRS。观察$('exampleAttr',函数(){
                的console.log('LOG2:',attrs.exampleId);
            });            VAR数据= {};
            对(在ATTRS变种I){
                VAR T = Object.prototype.toString.call(ATTRS [I]);
                如果(T =='的翻译:'和;!& T公司='[对象功能]'!)数据[I] = ATTRS [I]
            }
            的console.log(数据);
        }
    }
});


解决方案

在您的例子code有几个错误/改进:


  1. 您正在混合exampleAttr和exampleId

  2. 其更好的阅读传递价值回调$观察功能:

      ATTRS。观察$('exampleAttr',函数(newValue)以{
        / *使用为newValue这里,而不是attr​​s.exampleAttr * /
    });


下面是工作提琴:

I would like to be able to create a angularjs directive that in the end creates a HighCharts graph from the elements attributes. I have a directive working but any dynamically set attributes are returning undefined. In the end i want all the attributes on the element to be sent to a $http request as params.

I have tried using the $observe method and it does not seem to work, also i would like the attributes to be anything and not predefined.

See this fiddle: http://jsfiddle.net/F52SF/ and code below of directive:

myApp.directive('example', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            console.log('Log1:', attrs.exampleId);
            attrs.$observe('exampleAttr', function () {
                console.log('Log2:', attrs.exampleId);
            });

            var data = {};
            for(var i in attrs){
                var t = Object.prototype.toString.call( attrs[i] );
                if(t !== '[object Object]' && t != '[object Function]') data[i] = attrs[i];
            }
            console.log(data);
        }
    }
});
解决方案

In your example code there are couple of mistakes/improvements:

  1. You're mixing exampleAttr and exampleId
  2. Its better to read value passed to callback of $observe function:

    attrs.$observe('exampleAttr', function(newValue) {
        /* use newValue here instead of attrs.exampleAttr */
    });
    

Here is working fiddle: http://jsfiddle.net/F52SF/1/

这篇关于AngularJs无法读取动态设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 01:56