我编写了脚本来测试控制器之间的传递变量,所以我定义一个服务并在其上声明变量getContents
,然后将其传递给下一个控制器personController
,但是出了点问题,这是我的脚本:
<script>
angular.module("app", []).service("personService", function () {
var getContents = {};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.getContents = data;
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
$scope.GetContent();
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
出了什么问题?
注意:当我删除Service
时,控制器正常工作并从/Home/Get
获取数据。
编辑:这是我的编辑:
<script>
angular.module("app", []).service("personService", function () {
var Content = {};
return {
getContent: function () {
return Content;
},
setContent: function (value) {
Content = value;
}
};
})
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
debugger;
$http.get("/Home/Get").success(function (data) {
debugger;
console.log("successData :", data); //console did not log
personService.setContent(data);
console.log("ServiceData:",personService.getContent()) //console did not log too
$scope.Persons = data;
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
});
</script>
这是我的html :(更多帮助)
<div ng-app="app">
<div class="container" ng-controller="personController" ng-init=" GetContent()">
<div ng-show="!ShowForm">
<table class="table">
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in Persons">
<td>{{person.Name}}</td>
</tr>
</tbody>
</table>
</div>
</div>
答案 0 :(得分:4)
你必须退回服务
<强>服务强>
angular.module("app", []).service("personService", function () {
var content = {};
var person = {
setContent :function(item){
content = item;
}
getContent : function(){
return content;
};
};
return person;
})
<强>控制器强>
.controller("personController", function ($http, $scope, personService) {
$scope.GetContents = function () {
$http.get("/Home/Get").success(function (data) {
debugger;
personService.setContent(data); // set content to service..
$scope.Persons = data;
});
}
$scope.Save = function () {
$http.post("AddPerson",$scope.model).success(function (status) {
debugger;
console.log('status =', status);
$scope.ShowForm = false;
personService.getContent(); // get content from service..
});
}
$scope.AddPerson = function () {
$scope.ShowForm = true;
$scope.model = {};
}
将personService.getContent()定义为$ scope变量以显示在视图页面上。
$scope.content = personService.getContent();