簡體   English   中英

在Angular.js中的組件/控制器之間訪問對象

[英]Accessing objects between components/controllers in Angularjs

我需要在Angularjs中的控制器之間共享一些對象,並且做出了一些行得通的事情,但對我來說卻有點笨拙。 我想知道我所擁有的是否可以接受,或者是否有首選的方式可以做到。

在componentA中,我有一個要從componentB訪問的對象。

app.component("componentA", {
    controller: function ($scope, $rootScope, $compile) {

        //the object whose contents I want
        $scope.objectToAccess = {name: 'object', value: 3};

        //receives broadcast from componentB, returns the object
        $rootScope.$on("getObject", function () {
            $rootScope.$broadcast('receiveObject', $scope.objectToAccess);
        });
    }
}

app.component("componentB", {
    controller: function ($scope, $rootScope, $compile) {

        $scope.object = {name : null, value: null};

        //receives the broadcast of the object and sets the value
        $rootScope.$on("receiveObject", function (event,object) {
            console.log(object);
            $scope.object = object;
        });

        //broadcast to get the object contents
        $rootScope.$broadcast('getObject');   
    }
}

這行得通,但是在進行大量來回通信時感覺太復雜了。 Angular中是否有專門用於處理此類事情的東西,或者我認為可以接受的東西嗎?

我認為$ scope事件應用於訂閱但不請求數據更改的情況。

相反,您可以使用將保存數據並在控制器中引用它的服務。 由於服務是單例的,所以兩個控制器將共享同一實例,因此可以輕松共享數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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