1

为什么这在 AngularJS 中不起作用?

<div class="inputbox" ng-repeat="publisherParam in publisherParams">
    <div>
        <label>{{ publisherParam.label }}</label>
    </div>
    <div>
        <input type="text" name="{{ publisherParam.label }}" ng-model="{{ publisherParam.label }}" required />
    </div>
</div>
<div class="submitbox">
    <button class="purple-btn" ng-disabled="publisherForm.$invalid">
        Add Network
    </button>
</div>
4

2 回答 2

3
  1. 你不应该在 中使用{{ }}ng-model你应该写:ng-model="publisherParam.label"
  2. 您不能在输入名称中使用表达式,它需要是静态字符串以支持字段级验证。

如果您可以分享一个 jsFiddle,我很乐意为实际代码提供更多帮助。

于 2012-10-11T15:35:47.300 回答
0

听起来您想使用 ng-repeat 和 $index 来获取要放入表单输入字段名称的项目的索引。我不确定你到底想做什么,但希望这能让你朝着正确的方向前进......

编辑:此外,在 Angular 中提交表单时,输入的 name="" 是无关紧要的,因为您可以在 $scope 中获取要更改的整个对象并通过 AJAX 发送。

HTML

 

<form name="publisherForm" ng-submit="formSubmit()">
    <div class="inputbox" ng-repeat="publisherParam in publisherParams">
        <div>
            <label>{{publisherParam.label}}</label>
        </div>
        <div>
           <!-- use $index to get the index of the item in the array -->
           <!-- note, no {{}} inside of the ng-model tag. 
               That's being $eval'ed so no {{}} needed -->
            <input type="text" name="publisherParam_label_{{$index}}" ng-model="publisherParam.label" required />
        </div>
    </div>
    <!-- just an add button so you can see it work -->
    <button type="button" ng-click="addPublisherParam()">Add</button>
    <!-- your submit button -->
    <div class="submitbox">  
        <button class="purple-btn" type="submit ng-disabled="publisherForm.$invalid">
            Add Network
        </button>
    </div>
</form>

JS

app.controller('YourController', function($scope) {
   //this is the array you're displaying
   $scope.publisherParams = [
       { label: 'First Label' },
       { label: 'Second Label' }
   ];

   //just an indexer
   var p = 0;
   $scope.addPublisherParam = function(){
       //add a new publisher param.
       $scope.publisherParams.push({ label: 'New Label ' + p++ });
   };

   $scope.formSubmit = function(){
       //do something here.
   };
});
于 2012-10-11T16:32:10.337 回答