-1

我一直在为培训师开发一个应用程序,我遇到了可能很简单的问题,尽管我不知道如何解决这个问题并且我尝试了许多不同的解决方案。我注意到的是,当输入高于由 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>

这是 tha 角码:

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);
4

1 回答 1

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>,我也删除了它。希望这个重构的代码可以帮助你!

于 2013-09-20T17:24:06.593 回答