Javascript 如何从其他方法访问Angular.js$scope?
例如,我对我的服务器有这样的请求。作为响应,我将获得一个带有参数的对象数组:id、name和position。所有这些货物都放在一张桌子上。如果我以后决定更改数组,如何使用数组Javascript 如何从其他方法访问Angular.js$scope?,javascript,html,angularjs,Javascript,Html,Angularjs,例如,我对我的服务器有这样的请求。作为响应,我将获得一个带有参数的对象数组:id、name和position。所有这些货物都放在一张桌子上。如果我以后决定更改数组,如何使用数组$scope.employees 服务器的回答是: data = [{"id":1,"name":"Jack","position":"City guard"},{"id":2,"name":"Jim","position":"Sheriff"},{"id":4,"name":"Jack","position":"Crue
$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代码:
<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>
身份证件
名称
位置
{{employee.id}
{{employee.name}
{{employee.position}
按钮
其他操作方法应嵌套在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;
});
}
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"
});
}
还可以将$scope作为参数传递,如下所示:
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;
});
}
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"
});
}
如果该方法是“外部”的基本方法,那么在调用该函数时,除了将作用域传递给它之外,几乎没有其他方法。像这样的方法通常属于angular服务,如果您始终使用angular,那么访问$scope和其他angular位(使用$injector,您可以获得它们)会容易得多。我对angular和javascript非常陌生,因为我使用的是后端,所以如果您能为我的示例显示一些代码,效果会更好。