【发布时间】:2016-01-03 00:22:58
【问题描述】:
我正在尝试通过更改控制器的范围变量来学习添加 DOM 元素的 Angular 方法,该元素从服务返回的数据传递给指令。
我的服务
.factory('Poller', function($http,$q){
return {
poll : function(api){
var deferred = $q.defer();
$http.get(api).then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
}
});
我的控制器
.controller('accordion',['$scope','Poller','$timeout',function($scope,Poller,$timeout){
$scope.newdata = null;
function Repeater () {
$scope.$apply(function () {
Poller.poll('api/getupdates')
.then(function(data){
$scope.newdata = data;
});
});
};
$timeout(Repeater, 1000) ;
var timer = setInterval(Repeater, 11000);
我的指令
.directive( 'newreading', function () {
return {
scope: {'newdata' : '='},
templateURL : 'template\newreading.html',
link: function ( scope, element, attrs ) {
var el;
scope.$watch('newdata', function () {
console.log(scope.newdata);
});
}
};
});
HTML //注意:这是由 ng-repeat 完成的
<accordion-group id="Device 1">
<newreading ></newreading>
</accordion-group>
<accordion-group id="Device 2">
<newreading ></newreading>
</accordion-group>
<accordion-group id="Device3">
<newreading ></newreading>
</accordion-group>
<accordion-group id="Device4">
<newreading ></newreading>
</accordion-group>
我的 JSON 示例
{
"readings": [
"id": "Device2",
"T01": "3",
"L02": "35"
]
}
这里一切正常,我想完全不使用 jQuery(我知道 Angular 有 jQuery Lite)
我的问题
首先,这是使用 Angular JS 向 DOM 添加元素的正确方法吗?如果是,我将如何重用该指令?目前,scope.watch 会触发该函数 4 次(显然!!)。
我太困惑了,因为我找不到一种简单的方法来触发正确的指令来添加元素。
我浏览了文档的几个部分,发现 StackOverflow 问题建议编译和添加元素,我可以这样做,但我需要在所需的 div 中添加元素。
非常感谢任何帮助。
【问题讨论】:
标签: javascript angularjs dom angularjs-directive