[英]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.