Angular.js在长轮询更改监视值时更新ng类

Angular.js updating ng-class when long polling changes a watched value

本文关键字:监视 更新 ng js Angular      更新时间:2023-09-26

使用angular.js

我正在长时间轮询服务器,并且每当build_tag值增加时,我都希望更新视图中的一个类为"updated"的元素。

因此,当catalog.products[??].build_tag发生更改时,我正在努力寻找一种优雅的方法来添加更新的类。

<div ng-controller="MyAwesomeController as env">
    <div class="product-wrapper" ng-class="{'error': product.error, 'updated': HELP!! }" ng-repeat="product in env.catalog">
    <!-- show stuff in cool and interesting ways -->

环境控制器:

app.controller('EnvironmentController', ['$http', '$interval', function($http, $interval) {
    var vm = this;
    var pollingInterval = 5000;
    vm.catalog = {
        // only showing 2 products for the
        // sake of brevity. I normally have dozens
        // of products
        products: [{
            name: 'widget1',
            error: false,
            build_tag: 7
        }, {
            name: 'widget2',
            error: false,
            build_tag: 5
        }]
    };
    function fetchData() {
        $http.get('/builds.json').then(function (resolved) {
            if (resolved.status === 200) {
                vm.catalog = angular.merge(vm.catalog, resolved.data);
            }
        }, function (rejected) {
            ... do error stuff
        });
    }
    $interval(fetchData, pollingInterval);
... more controller stuff

这有道理吗?当我轮询服务器时,我会更新vm.config。我希望每个产品包装器都能看到它是build_tag。如果build_tag已经更改,我想将updated类添加到视图中的相应元素中。

您总是可以编写一个指令来添加类。

.directive('buildTagUpdated', [function() {
    return {
        link: function buildTagUpdatedLink(scope, element, attributes) {
            scope.$watch('buildTag', function(newValue, oldValue) {
                if (newValue !== oldValue) {
                    /**
                     * you can use element methods here 
                     * see https://docs.angularjs.org/api/ng/function/angular.element
                     */
                }
            });
        },
        restrict: 'A',
        scope: {
            buildTag: '='
        }
    };
}]);

然后在要更新的元素上,只需添加build-tag-updated="product.build_tag"