随着服务中的变量在agularjs中的变化,控制器中的变量不会更新

时间:2014-12-12 10:03:39

标签: angularjs

新手在这里!)

我有服务

angular.module('autotestApp').service('GroupPageService', function () {
    var group = "";

    this.list = function () {
        return group;
    };

    this.update = function (new_group) {
        group = new_group;
    };
});

控制器

angular.module('autotestApp').controller('GroupPageController', function ($scope, $http, $routeParams, GroupService, $modal, GroupPageService) {

    $scope.groupId = $routeParams.id;
    $scope.group = GroupPageService.list();

    var getGroup = function (id) {
        $http({
            method: "get",
            url: "/enterprises/_groups/"+id
        }).success(function (response) {
            GroupPageService.update(response.group);
        }).error(function () {
            console.log("Error while fetching data of one particular group")
        });
    };

    getGroup($scope.groupId);
}

我的逻辑是:

  1. getGroup()函数从Web API获取数据并更新变量" group"在服务中
  2. $ scope.group分配给service.list()函数
  3. 返回的数据

    正在从Web API正确返回数据,但其余部分存在问题。

    变量$ scope.group未更新

    如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

您需要在success方法中分配从API返回的数据。您为$ scope.group在顶部执行的第一个任务仅在控制器第一次运行时执行。之后没有更新$ scope.group的内容。

关于服务:当您想在整个应用中共享数据时,通常会使用服务。在您的情况下,如果您想要检索这些组一次,然后将您的服务注入多个控制器并使这些数据可用。

答案 1 :(得分:0)

您可以使用$watch来查看服务方法。

            $scope.$watch(function() {
                return GroupPageService.list();
            }, function(newValue, oldValue) {
                if (newValue !== oldValue) {
                     $scope.group = GroupPageService.list();
                }
            }, true);

答案 2 :(得分:0)

当您在服务中分配新值时,您似乎正在更改对该值的引用。您应该为代码工作做些什么,将您的组变量转换为对象:

app.service('GroupPageService', function () {
    var group = {name: "xxx"} ;

    this.list = function () {
          return group;
      };

    this.update = function (new_group) {
          group.name = new_group;
    };
});
相关问题