我正在尝试创建一个应用程序,每 10 秒左右轮询一次实时数据。如果数据发生变化,它应该在 View 中突出显示。我已经成功地解决了这个问题,但在 jQuery 的帮助下。我想用一个 Angular 模板来代替。
这是我的 Controller :
angular.module('myApp.controllers', [])
.controller('MainCtrl', ['$rootScope', 'liveDataPoller', function($rootScope, liveDataPoller) {
$rootScope.liveData = liveDataPoller.getData();
}]);
这是我的指令:
angular.module('myApp.directives', []).
directive('liveValue', function() {
return {
restrict: 'A',
scope: {
val: '='
},
link: function(scope, element, attrs) {
scope.$watch('val', function(newValue, oldValue) {
if(newValue && oldValue && (newValue !== oldValue)) {
if(newValue < oldValue) {
element.removeClass("up").addClass("down");
} else {
element.removeClass("down").addClass("up");
}
} else {
element.removeClass("down").removeClass("up");
}
});
}
}
});
这是我的观点:
<div live-value val="liveData.randomInteger">{{liveData.randomInteger}}</div>
是否可以将添加/删除类更改为使用 transclude 和模板?真的不想在其中混合使用 jQuery。
如果有任何不清楚的地方,请告诉我。
最佳答案
示例演示:http://plnkr.co/edit/uXhOceXYWLLkmRkzxx1h?p=preview
范围变量可用于跟踪新更改并使用双向绑定(bind)更新 html 中的类。
app.directive('liveValue', function() {
return {
restrict: 'E',
replace: true,
scope: {
data: '=', change:'='
},
template: '<div class="{{change}}">The value({{data}}) has gone: {{change}}</div>',
link: function(scope, element, attrs) {
scope.change = '';
scope.$watch('data', function (newValue, oldValue) {
if (newValue == oldValue) {
scope.change='nochange';
}else if(newValue<oldValue){
scope.change='down';
}else{
scope.change='up';
}
});
}
}
});
关于javascript - 如何在指令中使用 $watch 来更新类(无 jQuery)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23998087/