2016-05-25 72 views
0

我建立一個客戶端收集以下信息:更新數組內的對象AngularJS對象內

"name" : "Test client", 
"email" : "[email protected]", 
"position" : "Project Manger", 
"contacts" : [ 
    { 
     "name" : "asdf", 
     "email" : "[email protected]", 
     "tel" : "7877877878", 
     "title" : "asdf" 
    }, 
    { 
     "name" : "fdas", 
     "email" : "[email protected]", 
     "tel" : "7877877878", 
     "title" : "fdsa" 
    } 
], 

我希望能夠編輯/更新客戶端的接觸,但我我不知道如何做到這一點,因爲我有一個ng-repeat內部的表單,重複客戶端的聯繫。

<div ng-repeat="contact in contacts track by $index"> 
    <label>Name</label> 
    <input type="tel" ng-model="contact.name"> 
    <label>Telephone</label> 
    <input type="tel" ng-model="contact.tel"> 
    <label>Email</label> 
    <input type="email" ng-model="contact.email"> 
    <label>Title</label> 
    <input type="text" ng-model="contact.title"> 
    <md-button ng-click="save(contact)">Save</md-button> 
</div> 

和我的控制器:

'use strict' 

angular.module('myApp') 
.controller('ContactsCtrl', function($scope, $mdDialog, $mdMedia, client) { 

    $scope.client = client; 

    $scope.contacts = client.contacts; 


    $scope.save = (contact) => { 
    Clients.update({_id: client._id},{ 
     $set: { 
     contacts : contact 
     } 
    },function(err, data){ 
     if(err) return console.log(err); 
     console.log(data + " "); 
     $mdDialog.hide(data); 
    }); 
    } 

    $scope.cancel = function() { 
    $mdDialog.cancel(); 
    }; 

    $scope.hide = function() { 
    $mdDialog.hide(); 
    }; 
}); 

但是,當我按下save它取代單個對象的數組。

問題

我如何更新陣列是一個文檔內有一個形式,是內部的NG-重複現有的對象?

回答

2

變化的html:

<div ng-repeat="contact in contacts track by $index"> 
    <label>Name</label> 
    <input type="tel" ng-model="contact.name"> 
    <label>Telephone</label> 
    <input type="tel" ng-model="contact.tel"> 
    <label>Email</label> 
    <input type="email" ng-model="contact.email"> 
    <label>Title</label> 
    <input type="text" ng-model="contact.title"> 
    <md-button ng-click="save($index,contact)">Save</md-button> 
</div> 

並保存()函數來

$scope.save = (index,contact) => { 
    Clients.update({_id: client._id},{ 
     $set: { 
     contacts[index] : contact 
     } 
    },function(err, data){ 
     if(err) return console.log(err); 
     console.log(data + " "); 
     $mdDialog.hide(data); 
    }); 
    } 

希望它的伎倆。

+0

嗨,你的代碼是有道理的,但我不斷收到語法錯誤at'contacts [index]:contact' –

0

能夠做一些工作,但我不確定這是否是最佳選擇。

只需添加$indexsave功能時:

<md-button ng-click="save($index, contact)">Save</md-button>

,並在控制器中的保存功能:有

$scope.save = (index, contact) => { 
    $scope.client.contacts[index] = contact; 
    Clients.update({_id: client._id},{ 
    $set: { 
     contacts : $scope.client.contacts 
    } 
    },function(err, data){ 
    if(err) return console.log(err); 
    console.log(data + " "); 
    $mdDialog.hide(data); 
    }); 
}