角度更新服务中的var

时间:2015-08-12 12:27:15

标签: angularjs angular-services

我正在尝试提供服务,我可以检查建筑物是否更新。

所以我对serivce

进行了以下设置
define(['app'], function (app) {

    'use strict';
    app.service('BuildingService', function ($http, $q, $rootScope) {
        var buildings = null;
        var dirtyBuildings = [];
        var originalBuildings = [];


        this.getBuilding = function(id) {
            var deferred = $q.defer();
            // check if buildings were set
            if (buildings == null) getBuildings();

            // get index
            var index = arrayObjectIndexOfBuilding(buildings, { BuildingId: id });
            if (index < 0) deferred.reject("Building doesn't exist");
            // return object
            deferred.resolve(buildings[index]);

            return deferred.promise;
        }
        this.getBuildings = function () {
            var deferred = $q.defer();
            if (buildings == null) {
                $http.get('http://ws33177.sidmar.be/FMMService/api/Building').success(function (data) {
                    buildings = data;
                    deferred.resolve(buildings);
                }).error(function () {
                    deferred.reject();
                });
            } else {
                deferred.resolve(buildings);
            }
            return deferred.promise;

        }


        this.saveBuildings= function() {
            // TODO: Save logic
        }

        this.updateBuilding = function (newBuilding) {
            console.log("Updating");

            var deferred = $q.defer();

            // check if building exists in list
            var index = arrayObjectIndexOfBuilding(buildings, newBuilding);
            if (index < 0) deferred.reject("Building doesn't exist");
            console.log(newBuilding, buildings[index]) // <--- referenced in text

            // check if updated
            if (angular.equals(buildings[index], newBuilding)) {
                console.log("Same object");

            } else {
                // check if already dirty or not
                var dirtyIndex = arrayObjectIndexOfBuilding(dirtyBuildings, newBuilding);
                if (dirtyIndex < 0) {// new dirty
                    console.log("Something changed, new dirty");
                    // save in dirty list
                    dirtyBuildings.push(newBuilding);
                    // save original
                    originalBuildings.push(buildings[index]);
                } else {// already dirty
                    var originalIndex = arrayObjectIndexOfBuilding(originalBuildings, newBuilding);

                    // check if isn't reverted
                    if (angular.equals(originalBuildings[originalIndex], newBuilding)) {
                        console.log("Back to original");
                        // if same, remove from dirty buildings
                        dirtyBuildings.splice(dirtyIndex, 1);
                        // set old back
                        buildings[index] = originalBuildings[originalIndex];
                    } else {
                        console.log("Something changed, updating dirty");

                        // update the dirty building with latestd changes
                        dirtyBuildings[dirtyIndex] = newBuilding;
                    }
                }

                // update buildinglist
                buildings[index] = newBuilding;
            }

            $rootScope.$broadcast('updatedBuilding', { totalDirty: dirtyBuildings.length });
            deferred.resolve();

            return deferred.promise;
        }

        function arrayObjectIndexOfBuilding(arr, obj) {
            if (arr == null || obj == null) return "nothing";

            for (var i = 0; i < arr.length; i++) {
                if (arr[i].BuildingId == obj.BuildingId) {
                    return i;
                }
            }

            return -1;
        };
    });

    return app;
});
然后我通过以下方式获得建筑物:

BuildingService.getBuilding(page.options.BuildingId).then(function (result) {
    $scope.building = result
    $scope.$watch('building', function (newVal) {
        BuildingService.updateBuilding(newVal);
    }, true);
}, function () {
    ons.notification.alert({ message: 'An error has occurred!' });
});

构建有一个名为score的值(所以$scope.building.score)但是当我更新该值时,我的服务中buildings var中的原始值已经更新。所以chcek总是返回Same object

我可能做错了什么?

1 个答案:

答案 0 :(得分:1)

每次调用BuildingService.getBuildings方法时,您都会创建一个新手表。 而是在承诺成功回调之外创建手表。

$scope.property = 'score';
var buildingWatch;
BuildingService.getBuilding(page.options.BuildingId).then(function (result) {
    $scope.building = result;
}, function () {
    ons.notification.alert({ message: 'An error has occurred!' });
});


$scope.$watch('property', function (newVal) {
    if (buildingWatch) {
      buildingWatch();
    }
    buildingWatch = $scope.$watch('building.' + newVal , function (newVal) {
      BuildingService.updateBuilding(newVal);
    }, true);
    BuildingService.updateBuilding(newVal);
}, true);

如果您想要观察动态创建的属性,我建议在另一个内部创建一个新手表,并在每次属性更改时将其删除