[英]AngularJS DOM manipulation using existing directive
我正在尝试通过从控制器更改范围变量来学习使用从服务返回的数据添加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中添加元素。
任何帮助深表感谢。
在您的指令定义中,您编写了scope: {'newdata' : '='}
。 这将做的是创建一个隔离的范围,其中$scope.newdata
与newreading
元素的newdata
属性双向绑定。
因此,如果你的HTML没有说<newreading newdata="someVariableOnTheScope"></newreading>
这没有意义。 我不知道你的accordion
控制器的作用范围,所以我不能给你更具体的建议。
由于您使用的是相同的模板,因此您似乎不需要额外的新读数指令。 您只需要显示额外的读数。 因此,您应该更新基础模型,您的视图将自行更新。 这是Angular的神奇之处。
额外的读数可以添加如下(假设newData
包含新的读数):
// create an object so you can lookup a device by id
var devicesById = _.indexBy($scope.data,'_id');
_.each(newData,function(device) {
// add the new readings to the readings of the device with the correct id
Array.prototype.push.apply(devicesById[device._id].readings,device.readings);
});
一个傻瓜: http ://plnkr.co/edit/iKtmrToz4fkJ46bVfcjX
一些额外的提示:
attrs
或element
请不要在链接函数中编写代码。 在指令的控制器中执行此操作 $scope.$apply
如果您在AngularJS范围之外执行操作,则需要$scope.$apply
。 你基本上是对Angular说:我在这里做的事情可能已经改变了你所知道的DOM,再次同步。 这在使用其他库(例如JQuery)时非常有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.