gpt4 book ai didi

javascript - 如何从其他方法访问 Angular.js $scope?

转载 作者:行者123 更新时间:2023-11-28 00:27:44 25 4
gpt4 key购买 nike

例如,我向我的服务器发出这样的请求。作为响应,我将获得带有参数的对象数组:id、名称和位置。所有这些都加载到一个表中。如果我稍后决定更改数组 $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>

最佳答案

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"
});
}

关于javascript - 如何从其他方法访问 Angular.js $scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29328368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com