2016-03-05 58 views
0

我試圖給ng-repeat數組添加一個新對象。該數組是通過$ http請求獲取的數據創建的。我需要能夠將我在對話框中輸入的數據傳遞給一個函數,然後將這些數據作爲對象推送到數組並更新視圖。我可以在控制檯中記錄輸入的值,甚至當我登錄數組時,它將顯示更新的值,但它不會更新視圖。此外,如果使用不在對話框中的按鈕添加對象,它將更新數組。在角度材質對話框數據輸入/推後更新ng-repeat

UPDATE

查看與Chrome的角NG-檢查器中的範圍的概述之後,我可以看到,新的對象被添加到陣列控制器的範圍作爲元件,其中的母體內ng-repeat發生。 ng-repeat發生的元素有自己的範圍,我可以看到數組沒有在那裏更新。我需要這個數組成爲更新的數組,因爲那是ng-repeat的地方,而這正是正在查看的數據。我仍然有點困惑於如何可以有兩個相同的陣列,其中一個改變而另一個不改變。當我將對象推到'$ scope.plots'時,我需要定位ng-repeat父元素的範圍。我仍然沒有找到一個好辦法來做到這一點。

這裏是我的對話框

function showAdd(ev) { 
     $mdDialog 
      .show({ 
       controller: DialogController, 
       templateUrl: '/templates/addDialog.html', //contains inputs that are modeled to values as seen in the push function below. A button calls addPlant() 
       targetEvent: ev, 
       clickOutsideToClose: true, 
       openFrom: 'left' 
      }).then(function(added) { 
       newPlant(added); 
     }) 
    } 

這裏是我的對話控制器

function DialogController($scope, $mdDialog, $http) { 
$scope.addPlant = function (added) { 
    for (var i = 0; i < added.quantity; i++) { 
     $http.post('/addPlant', added).then(function() { //this is just posting the data to a database, not related to the issue. 
       $mdDialog.hide(added); 
      } 
     }); 
    } 
}; 

和推動作用

var newPlant = function(added) { 
     $scope.plots.push({ 
      'plot': added.plot, 
      'varieties': [{ 
       'count': added.quantity, 
       'variety': added.variety 
      }], 
      'count': added.quantity 
     }); 

回答

0

我最終不得不創建一個服務並從rootScope廣播添加的對象。我爲偵聽廣播的ng-repeat元素創建了一個單獨的控制器。

當對話框關閉時,它解決了將表單數據傳遞給服務的承諾。

$mdDialog 
     .show({ 
      controller: 'DialogCtrl as dc', 
      templateUrl: '/templates/addDialog.html', 
      targetEvent: ev, 
      clickOutsideToClose: true, 
      openFrom: 'left' 
     }).then(function(added) { 
      addPlant.prepForBroadcast(added) //calling service in promise, passing 'added' input values 
    }) 

我創建了一個服務來廣播對象

var myApp= angular.module('myApp'); 

myApp.factory('addPlant', ['$rootScope', function($rootScope) { 
    var box= {}; //I like to call the designated factory object a 'box' 
    box.newPlant = {}; 

    box.prepForBroadcast = function(added) { 
     box.newPlant = added; 
      this.broadcastItem(); 
    }; 

    box.broadcastItem = function() { 
     $rootScope.$broadcast('broadcast'); 
    }; 
    return box; //ship out the box with the newPlant 
}]); 

而對於NG-重複元件的單獨的控制器,收聽廣播

myApp.controller('ListCtrl', ['$scope','addPlant', function($scope, addPlant) { 

$scope.$on('broadcast', function() { //listening for broadcast 
     $scope.plots.push({ 
      'plot': addPlant.newPlant.plot, 
      'count': addPlant.newPlant.quantity, 
      'varieties': [{ 
       'variety': addPlant.newPlant.variety, 
       'count': addPlant.newPlant.quantity 
      }] 
     }); 
    }) 
}]); 
相關問題