新手在这里!)
我有服务:
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);
}
我的逻辑是:
正在从Web API正确返回数据,但其余部分存在问题。
变量$ scope.group未更新
如何解决这个问题?
答案 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;
};
});