javascript - 如何在指令中使用 $watch 来更新类(无 jQuery)?

标签 javascript angularjs angularjs-directive

我正在尝试创建一个应用程序,每 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/

相关文章:

javascript - 组合 jQuery 对象

javascript - 以可变 Angular 存储表单数据

javascript - 如何在 angular1 中附加动态 html 和动态数据?

javascript - 格式化 AngularJS 指令模板的方法

javascript - Angular 服务导致错误

javascript - 如何向动态图表添加图例

javascript - 获取分配给变量函数的名称

javascript - 将多个循环转换为一个警报

javascript - AngularJS 自定义表单验证指令在我的模式中不起作用

javascript - 将数据数组从 Controller 传递到自定义指令?