AngularJS:如何在控制器之間傳遞變量?

本文翻譯自:AngularJS: How can I pass variables between controllers?

I have two Angular controllers: 我有兩個Angular控制器:

function Ctrl1($scope) {
    $scope.prop1 = "First";
}

function Ctrl2($scope) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

I can't use Ctrl1 inside Ctrl2 because it is undefined. 我不能使用Ctrl1裏面Ctrl2 ,因爲它是不確定的。 However if I try to pass it in like so… 但是,如果我嘗試像這樣傳遞它…

function Ctrl2($scope, Ctrl1) {
    $scope.prop2 = "Second";
    $scope.both = Ctrl1.prop1 + $scope.prop2; //This is what I would like to do ideally
}

I get an error. 我得到一個錯誤。 Does anyone know how to do this? 有誰知道如何做到這一點?

Doing 在做

Ctrl2.prototype = new Ctrl1();

Also fails. 也失敗。

NOTE: These controllers are not nested inside each other. 注意:這些控制器彼此之間不嵌套。


#1樓

參考:https://stackoom.com/question/oO44/AngularJS-如何在控制器之間傳遞變量


#2樓

One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it. 在多個控制器之間共享變量的一種方法是創建服務並將其注入到要使用它的任何控制器中。

Simple service example: 簡單服務示例:

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

Using the service in a controller: 在控制器中使用服務:

function Ctrl2($scope, sharedProperties) {
    $scope.prop2 = "Second";
    $scope.both = sharedProperties.getProperty() + $scope.prop2;
}

This is described very nicely in this blog (Lesson 2 and on in particular). 這個博客對此進行了很好的描述(特別是第2課)。

I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference. 我發現,如果要跨多個控制器綁定到這些屬性,則如果綁定到對象的屬性而不是原始類型(布爾,字符串,數字)來保留綁定的引用,則效果更好。

Example: var property = { Property1: 'First' }; 示例: var property = { Property1: 'First' }; instead of var property = 'First'; 而不是var property = 'First'; .


UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of: 更新:爲了(希望)使事情變得更清楚, 這是一個小提琴 ,其中顯示了以下示例:

  • Binding to static copies of the shared value (in myController1) 綁定到共享值的靜態副本(在myController1中)
    • Binding to a primitive (string) 綁定到原語(字符串)
    • Binding to an object's property (saved to a scope variable) 綁定到對象的屬性(保存到範圍變量)
  • Binding to shared values that update the UI as the values are updated (in myController2) 綁定到在更新值時更新UI的共享值(在myController2中)
    • Binding to a function that returns a primitive (string) 綁定到返回原語(字符串)的函數
    • Binding to the object's property 綁定到對象的屬性
    • Two way binding to an object's property 雙向綁定到對象的屬性

#3樓

If you don't want to make service then you can do like this. 如果您不想提供服務,則可以這樣做。

var scope = angular.element("#another ctrl scope element id.").scope();
scope.plean_assign = some_value;

#4樓

Couldn't you also make the property part of the scopes parent? 您是否也可以將該屬性作爲合併範圍的父級?

$scope.$parent.property = somevalue;

I'm not saying it's right but it works. 我並不是說這是正確的,但是可以。


#5樓

--- I know this answer is not for this question, but I want people who reads this question and want to handle Services such as Factories to avoid trouble doing this ---- ---我知道這個答案不是針對這個問題的,但是我希望那些讀過這個問題並希望處理諸如工廠之類的服務的人避免這樣做的麻煩----

For this you will need to use a Service or a Factory. 爲此,您將需要使用服務或工廠。

The services are the BEST PRACTICE to share data between not nested controllers. 這些服務是在非嵌套控制器之間共享數據的最佳實踐

A very very good annotation on this topic about data sharing is how to declare objects. 關於數據共享的這個主題的一個很好的註釋是如何聲明對象。 I was unlucky because I fell in a AngularJS trap before I read about it, and I was very frustrated. 我很不幸,因爲在我讀到它之前就陷入了AngularJS陷阱,我感到非常沮喪。 So let me help you avoid this trouble. 因此,讓我幫助您避免這種麻煩。

I read from the "ng-book: The complete book on AngularJS" that AngularJS ng-models that are created in controllers as bare-data are WRONG! 我從《 ng書:關於AngularJS的完整書》中讀到,在控制器中作爲裸數據創建的AngularJS ng模型是錯誤的!

A $scope element should be created like this: $ scope元素應這樣創建:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // best practice, always use a model
  $scope.someModel = {
    someValue: 'hello computer'
  });

And not like this: 而且不是這樣的:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // anti-pattern, bare value
  $scope.someBareValue = 'hello computer';
  };
});

This is because it is recomended(BEST PRACTICE) for the DOM(html document) to contain the calls as 這是因爲建議將DOM(html文檔)包含爲

<div ng-model="someModel.someValue"></div>  //NOTICE THE DOT.

This is very helpful for nested controllers if you want your child controller to be able to change an object from the parent controller.... 如果希望子控制器能夠從父控制器更改對象,這對於嵌套控制器非常有用。

But in your case you don't want nested scopes, but there is a similar aspect to get objects from services to the controllers. 但是在您的情況下,您不需要嵌套作用域,但是有一個相似的方面可以將對象從服務獲取到控制器。

Lets say you have your service 'Factory' and in the return space there is an objectA that contains objectB that contains objectC. 假設您擁有服務“工廠”,並且在返回空間中有一個objectA,其中objectB包含objectC。

If from your controller you want to GET the objectC into your scope, is a mistake to say: 如果您想從您的控制器中將objectC放入您的作用域,則錯誤地說:

$scope.neededObjectInController = Factory.objectA.objectB.objectC;

That wont work... Instead use only one dot. 那行不通...而是隻使用一個點。

$scope.neededObjectInController = Factory.ObjectA;

Then, in the DOM you can call objectC from objectA. 然後,在DOM中,您可以從objectA調用objectC。 This is a best practice related to factories, and most important, it will help to avoid unexpected and non-catchable errors. 這是與工廠相關的最佳實踐,最重要的是, 它將有助於避免意外的和不可捕獲的錯誤。


#6樓

You could do that with services or factories. 您可以通過服務或工廠來做到這一點。 They are essentially the same apart for some core differences. 它們之間基本相同,只是存在一些核心差異。 I found this explanation on thinkster.io to be the easiest to follow. 我發現thinkster.io上的這種解釋最容易理解 Simple, to the point and effective. 簡單,要點和有效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章