How to share the $scope variable of one controller with another in AngularJS?

北战南征 提交于 2019-12-28 05:48:08

问题


I have this:

app.controller('foo1', function ($scope) {
  $scope.bar = 'foo';
});
app.controller('foo2', function ($scope) {
  // want to access the $scope of foo1 here, to access bar
});

How would I accomplish this?


回答1:


You could use an Angular Service to share variable acrosss multiple controllers.

angular.module('myApp', [])
.service('User', function () {
    return {};
})

To share the data among independent controllers, Services can be used. Create a service with the data model that needs to be shared. Inject the service in the respective controllers.

function ControllerA($scope, User) {
    $scope.user = User;
    $scope.user.firstname = "Vinoth";
}

function ControllerB($scope, User) {
    $scope.user = User;
    $scope.user.lastname = "Babu";        
}



回答2:


You just can use $emit/$broadcast for translate changes of data from one controller scope to another. Or just store these variables on $rootScope.




回答3:


app.controller('foo2', function ($scope) {
    $scope.$$prevSibling.bar="bar"
});


来源:https://stackoverflow.com/questions/22584342/how-to-share-the-scope-variable-of-one-controller-with-another-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!