我希望能够创建,到底从属性的元素创建HighCharts图的angularjs指令。我有一个指导工作,但任何动态设置属性返回undefined。最后,我希望所有的元素的属性被发送到一个$ http请求的PARAMS。
我已经使用$观察方法尝试和它似乎并没有工作,还我想的属性是什么,而不是predefined。
看到这个小提琴: http://jsfiddle.net/F52SF/ 并低于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有几个错误/改进:
您正在混合exampleAttr和exampleId其更好的阅读传递价值回调$观察功能:
ATTRS。观察$('exampleAttr',函数(newValue)以{ / *使用为newValue这里,而不是attrs.exampleAttr * /});
下面是工作提琴: http://jsfiddle.net/F52SF/1/
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:
You're mixing exampleAttr and exampleIdIts 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/