2016-03-05 57 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 
      }] 
     }); 
    }) 
}]); 
相关问题