簡體   English   中英

如何在 AngularJS 中與另一個控制器共享 $scope 變量?

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

我有這個:

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

我將如何做到這一點?

您可以使用 Angular 服務在多個控制器之間共享變量。

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

為了在獨立控制器之間共享數據,可以使用服務。 使用需要共享的數據模型創建服務。 在各自的控制器中注入服務。

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

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

您只需使用$emit/$broadcast將數據更改從一個控制器范圍轉換為另一個控制器范圍。 或者只是將這些變量存儲在 $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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM