2015-10-07 58 views
0

HTML的陣列: -角-JS無法將數據推入控制器

<div ng-controller="countryController"> 
     {{name}} 
     <ul> 
      <li ng-repeat="country in countries"> 
       {{ country.name }} 
       <ul ng-show="country.states.length > 0"> 
        <li ng-repeat="state in country.states"> 
         {{ state.name }} 
        </li> 
       </ul> 
       <input type="text" ng-model="newState"> 
       <a href ng-click="addStateState(country)">Add </a> 
       {{newState}} 
      </li> 
     </ul> 
    </div> 

當我在它出現在客戶端newState模型鍵。 現在我嘗試將該值存入控制器並嘗試推入狀態數組,但無法將其添加到狀態數組中。

JS控制器: -

myApp.factory('countryService', function($http){ 
var baseUrl = 'services/' 
return { 
    getCountries : function(){ 
     return $http.get(baseUrl + 'getcountries.php'); 
    } 
}; 

});

myApp.controller('countryController', function($scope, countryService){ 
countryService.getCountries().success(function(data){ 
    $scope.countries = data; 
}); 

$scope.addStateState = function(country){ 
    country.states.push({'name' : $scope.newState}); 
    $scope.newState = ""; 
}; 

});

+0

能否請你解釋你所得到的錯誤?它看起來不錯。 – frosty

+0

一個Codepen或者一個plunkr會非常有幫助。 –

+0

@Mike是對的。在將來做一個plunkr併發布它使其他人更容易給予回答。 –

回答

0

您的主要問題是您的$ scope.newState在$ scope.newStateState函數內不可用。在$ scope函數內操作像$ scope這樣的對象是不好的做法。實際上,您正在創建多個與注入的$ scope不同的多個對象;否則,兩個不同國家的輸入框應該匹配。

下面的工作Plunkr。

http://plnkr.co/edit/HG3zWG?p=preview

JS:

angular.module('myApp',[]) 
.controller('countryController', function($scope){ 
    $scope.countries = [ 
     { name: 'USA', states:[ 
      {name: 'Virginia'}, 
      {name: 'Utah'} 
     ] 
     }, 
     { name: 'Brazil', states:[ 
      {name: 'Pernabuco'} 
     ] 
     } 
    ]; 

    $scope.addStateState = function(country, data){ 
    country.states.push({'name' : data.newState}); 
    data.newState = ""; 
    }; 
}); 

HTML:

<div ng-controller="countryController"> 
     {{name}} 
       <ul> 
     <li ng-repeat="country in countries"> 
       {{ country.name }} 
          <ul ng-show="country.states.length > 0"> 
      <li ng-repeat="state in country.states"> 
         {{ state.name }} 
        </li> 
      </ul> 
      <input type="text" ng-model="data.newState" /> 
      <a href="" ng-click="addStateState(country, data)">Add </a> 

       {{data.newState}} 
      </li> 
     </ul> 
    </div> 
0

當你處理事情像NG重複,NG-IF或NG-包括他們各自創建一個新的範圍。這意味着當您嘗試綁定到該範圍的根級別上的原語時,它將在您更新該值時得到解除引用。所以,你需要把你的基元放入一個對象中。約翰帕帕的風格指南建議在你的示波器上製作一個「虛擬」屬性。 vm代表視圖模型。

這是一個如何使用它的jsfiddle。

http://jsfiddle.net/fbLycnpg/

vm.newState 
+0

很好的描述。你要在ng-conf主持?你去年很熱鬧#endofconversationinstackoverflowcomment –

+0

哇!謝謝@chris。這是我的一天,而這一天剛剛開始。 – frosty