ng-model不与ng-repeat通信

时间:2013-09-20 15:34:56

标签: angularjs angularjs-ng-repeat

我一直在研究培训师的应用程序,我遇到的可能很简单 问题,尽管我不知道如何解决这个问题,我尝试了许多不同的解决方案。 我注意到的是,当输入在ng-repeat生成的列表之上时,它工作得很好,但我希望列表在输入下。 任何建议将不胜感激。 这是现在的HTML代码:

<html ng-app="trainingSupport">
<form method="post" enctype="multipart/form-data" action="" ng-controller="addOffer">
<div class="span40"><input type="text" ng-model="newOffers.offerName" name="offer" class='span48 offer-in'></div>
<div class="span8 options-btn">
<div class="pencil-offer"><i class="icon-pencil icon-offer"></i></div>
<button ng-click="newOffer()" type='submit' class="btn save-offer"><i class="icon-save"></i></button>
<button type="submit" class="btn trash-offer"><i class="icon-trash"></i></button>
</div>
</form>
</div>

<div class="row-fluid">
<ol class="span48" ng-controller="addOffer">
<li ng-repeat="offer in offers" ng-bind='offer.offerName' class="unbold f-pt-sans offer-list"></li>
</ol>
</html>

这里是角度代码:

var trainingSupport = angular.module('trainingSupport', []);
function addOffer($scope){

$scope.offers=[
{id:0, offerName:"szkolenie z pieczenia indyka"},
{id:1, offerName:"szkolenie z gaszenia wodą"},
{id:2, offerName:"szkolenia z bicia konia"}
];

$scope.newOffer = function(){

$scope.offers.push({


offerName: $scope.newOffers.offerName
});

$scope.newOffers.offerName='';

}

}
trainingSupport.controller("addOffer", addOffer);

1 个答案:

答案 0 :(得分:1)

我为此创建了一个jsFiddle,为了更好的可读性,将代码简化为基础知识。 http://jsfiddle.net/yhx8h/1/

我重构了你的控制器,它现在更干净了。

var trainingSupport = angular.module('trainingSupport', []);

trainingSupport.controller("addOfferCtrl", 
function AddOfferCtrl($scope){       

    //this variable is bound to your input
    $scope.newOfferName = '';       

    $scope.offers=[
       {id:0, offerName:"szkolenie z pieczenia indyka"},
       {id:1, offerName:"szkolenie z gaszenia wodą"},
       {id:2, offerName:"szkolenia z bicia konia"}
    ];

    $scope.newOffer = function(){
      //handy little method to grab the max id in your array
      var newId = Math.max.apply(null,$scope.offers.map(function(item){return item.id})); 

      //increment the id, and add new entry to the array
      $scope.offers.push(
        {id: newId + 1, offerName: $scope.newOfferName }
      );     
    };

});

HTML:

<div ng-app="trainingSupport" ng-controller="addOfferCtrl">

  <input type="text" ng-model="newOfferName" />
  <button ng-click="newOffer()" type="button" text="click me to add offer" ></button>

  <ol>
    <li ng-repeat="offer in offers">{{offer.offerName}}</li>
  </ol>

</div>

我将您的输入绑定到单独的变量newOfferName,并删除了额外的提交按钮和<form>标记。从您发布的代码判断,我不明白为什么您需要在此实现中使用<form>标记或提交按钮。相反,您可以将ng-click函数绑定到一个按钮(或几乎任何其他类型的元素),它将处理更新数组并重新绑定列表。最后,我不明白为什么你需要ng-bind <li ng-repeat>,我也删除了{{1}}。希望这个重构的代码可以帮助你!