質問

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?

役に立ちましたか?

解決

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

他のヒント

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

app.controller('foo2', function ($scope) {
    $scope.$$prevSibling.bar="bar"
});
app.controller("firstCtrl", function ($scope) {
    $scope.func = function () {
        // pass scope variable(s) here
        $scope.$broadcast('parentmethod', { key: value });
    }
})

app.controller("secondCtrl", function ($scope) {
    $scope.$on('parentmethod', function (event, args) {
        // access scope variable using args
        $scope.targetVar = args.key;
    })
})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top