简体   繁体   中英

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

Using angular.js

I am long polling a server, and want to update an element in view, with a class of 'updated', whenever a build_tag value has been incremented.

So I'm struggling, trying to find an elegant way to add an updated class, when catalog.products[??].build_tag has been changed.

<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 -->

EnvironmentController:

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

Does that make sense? When I poll the server, I update vm.config . I expect each product-wrapper to watch it's build_tag . And I want to add an updated class to the respective element in the view if the build_tag has changed.

You can always write a directive to add the class.

.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: '='
        }
    };
}]);

Then on the element you want to update, just add the build-tag-updated="product.build_tag"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM