例如,我对我的服务器有这样的请求。作为回应,我将获得一个带参数的对象数组:id,name和position。所有这些都加载到表中。如果我决定稍后更改它,我如何使用数组$scope.employees
进行操作?
来自服务器的答案是:
data = [{"id":1,"name":"Jack","position":"City guard"},{"id":2,"name":"Jim","position":"Sheriff"},{"id":4,"name":"Jack","position":"Cruel genius"},{"id":7,"name":"Guy","position":"Manager"}]
如何确定,该请求已经发布到表中,所以我可以执行一些以后的操作?
angular
.module('MyApp', [])
.controller('MyController', ['$scope', '$http', MyController]);
function MyController ($scope, $http) {
$http.get("/servlet").success(function(data){
$scope.employees = data;
});
}
function otherOperation () {
$scope.employees.push({
id : 5,
name : "John",
position : "Manager"
});
}
HTML code:
<div id="content" ng-controller='MyController'>
<table id="table">
<tr>
<th> ID </th>
<th> Name </th>
<th> Position </th>
</tr>
<tr ng-repeat="employee in employees">
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.position}}</td>
</tr>
</table>
<button ng-click="otherOperation"> Button </button>
</div>
答案 0 :(得分:1)
otherOperation方法应该嵌套在MyController中,如下所示:
angular
.module('MyApp', [])
.controller('MyController', ['$scope', '$http', MyController]);
function MyController ($scope, $http) {
function otherOperation () {
$scope.employees.push({
id : 5,
name : "John",
position : "Manager"
});
}
$http.get("/servlet").success(function(data){
$scope.employees = data;
});
}
您还可以将$ scope作为参数传递,如下所示:
angular
.module('MyApp', [])
.controller('MyController', ['$scope', '$http', MyController]);
function MyController ($scope, $http) {
$http.get("/servlet").success(function(data){
$scope.employees = data;
});
otherOperation($scope);
}
function otherOperation ($scope) {
$scope.employees.push({
id : 5,
name : "John",
position : "Manager"
});
}