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

How to access Angular.js $scope from other method?

本文关键字:Angular js scope 访问 方法 其他      更新时间:2023-09-26

例如,我的服务器收到了这样的请求。作为响应,我将获得一个带有参数的对象数组: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代码:

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