簡體   English   中英

如何將值傳遞給其他控制器?

[英]How to pass the value into other controller?

我認為這些信息不足以完全理解,但我只是對此提供了一些指導。 或者如果您願意,我可以與您共享完整的代碼

我正在嘗試將此數組從API放入賣方數組。

    this.fetchSellers = function () {
        var date = new Date().toISOString();
        $http.get('/api/sellers', {params: {auctionDate: date}})
            .success(function (sellers) {
                sellers && sellers.length && ($scope.sellers = sellers);
            });
    };

我試圖將值Seller.symbol之一放入下面的數組列表中。 在此處輸入圖片說明

$scope.sellers = []

它能夠像這樣加載到ng-option

<select class="form-control" ng-model="auction.seller" ng-options="o.id as o.symbol for o in sellers" required></select>

在此處輸入圖片說明

但是問題是,我無法將值傳遞到表中的另一個控制器。
在此處輸入圖片說明

HTML代碼

   <tbody class="auction-group" ng-repeat="a in auctions">
    <tr>
        @*auction *@
    <td>{{ acv('auctionDate', a) }}</td>
        @*seller*@
    <td>{{ a.seller }}</td>

ng代碼

 this.tableComplexFieldDict = {

        auctionDate: {
            label: 'Auction',
            cacheKey: 'auctionDate',
            getCacheValue: function (a) {
                return moment(a.startAt).format('MM/DD/YY');
            }
        },

        facility: {
            label: 'Facility',
            cacheKey: 'facility',
            getCacheValue: _.property('contract.facility')
        },

        seller: {
            label: 'Seller',
            cacheKey: 'seller',
            getCacheValue: function (a) {
                return a.seller;
            }
        },

為此,您必須使用其他服務。 理想情況下,您可以在控制器之間傳遞數據,反之亦然。 因此,只需創建另一個服務並將其包含在您要向其傳遞數據的控制器中即可。

這是例子

要么

 // declare the app with no dependencies var myApp = angular.module('myApp', []); myApp.factory('Data', function(){ return { FirstName: '' }; }); myApp.controller('one', function( $scope, Data ){ $scope.Data = Data; }); myApp.controller('two', function( $scope, Data ){ $scope.Data = Data; }); 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script> </head> <body> <div ng-app="myApp"> <h3>write something in text box it will be printed by both controller</h3> <div ng-controller="one"> <input type="text" ng-model="Data.FirstName"><!-- Input entered here --> <br>Controller 1 : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here --> </div> <hr> <div ng-controller="two"> Controller 2: {{Data.FirstName}}<!-- How do I automatically updated it here? --> </div> </div> </body> </html> 

可以通過3種方式在控制器之間傳遞數據:

  • 兩個控制器都使用帶有設置獲取數據功能的共享服務

  • 使用通過根范圍的直接數據綁定作為介質來存儲從中讀取的數據

(可怕地侵犯了根范圍)

  • 通過事件

對我來說,最佳實踐是使用存儲和讀取服務;)

暫無
暫無

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

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