[英]How to access Angular.js $scope from other method?
For example, I have such request to my server. 例如,我对服务器有这样的请求。 As a response, I will get an array of objects with parameters: id, name and position.
作为响应,我将获得带有参数的对象数组:id,名称和位置。 All of these loads into a table.
所有这些都装入表中。 How can I manipulate with an array
$scope.employees
if i will decide to change it later? 如果我以后决定更改它,如何使用数组
$scope.employees
操作?
An answer from server is: 来自服务器的答案是:
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"}]
And how to be sure, that request is already posted into a table, so i can perform some later operations? 以及如何确保该请求已经发布到表中,以便以后可以执行一些操作?
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: HTML代码:
<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>
The otherOperation method should be nested inside MyController, like this: 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;
});
}
You could also pass the $scope as a parameter, like this: 您还可以将$ 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"
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.