将rootScope值从一个控制器传递到另一个控制器

时间:2017-06-09 07:03:50

标签: angularjs

我试图使用$ rootscope将值从控制器传递给另一个我所做的是首先我像这样初始化rootScope

app.run(function ($rootScope) {
    $rootScope.emp=0 ;
});

然后我在我的一个控制器中更改rootScope的值,就像这样

app.controller("datatableController", function ($scope, DTOptionsBuilder, $http, $rootScope) {
 $scope.update = function (data) {
        alert(data);
        $scope.message = $http.post('http://localhost:5000/api/employee/view', data).
            then(function (response) {
                $scope.userEdit = response.data;
                $rootScope.emp=$scope.userEdit[0].id;
                alert($rootScope.emp);
            });
        window.location.href = "updateEmployee.html";

    };
});

然后我试图在我的第二个控制器中访问这个更改的$ rootScope.emp值但是获取我在初始化时设置的值0

app.controller("UpdateController", function ($scope, $http, $rootScope) {

    $scope.userid=$rootScope.emp;
    alert($scope.userid);
});

1 个答案:

答案 0 :(得分:0)

试试这个:

app.controller("datatableController", function ($scope, DTOptionsBuilder, $http, $rootScope) {
 $scope.update = function (data) {
    alert(data);
    $scope.message = $http.post('http://localhost:5000/api/employee/view', data).
        then(function (response) {
            $scope.userEdit = response.data;
            $rootScope.$apply(function(){
                $rootScope.emp=$scope.userEdit[0].id;
            });
            alert($rootScope.emp);
        });
    window.location.href = "updateEmployee.html";

};
});

Detailed Answer can be found here

相关问题