ng-models在ng-repeat中命名冲突

时间:2015-11-12 04:26:02

标签: angularjs

http://plnkr.co/edit/2UFfaG?p=preview

我使用这个示例代码构建了一个简单的应用程序,我注意到当您使用循环重复的ng-model时,编辑功能不起作用。我知道这一点,因为我尝试在ng-repeat循环之外使用ng-models,它运行得很好。因此,当您有两个具有相同名称的ng-model实例时,当您尝试从视图中返回值时,会返回空白数据。

这是我的观点:

<ul ng-repeat="notes in notes">
    <li>
      <span ng-hide="editing" ng-click="editing = true">{{note.name}} | {{note.content}}</span>
      <form ng-show="editing" ng-submit="editing = false">
        <label>Name:</label>
        <input type="text" ng-model="name" placeholder="Name" ng-required/>
        <label>Content:</label>
        <input type="date" ng-model="content" placeholder="Content" ng-required/>
        <br/>
        <button class="btn" ng-click="edit(note.id)">Save</button>
      </form>
    </li>

</ul>

这是我的编辑方法:

$scope.edit = function (id) {
    var note = notesRef.child(id);
    var newNote= {

            name : $scope.name,
            content : $scope.content

        }
    };

    note.update(newNote);
};

当我在ng-repeat中引用ng-model时,我只能因某种原因得到null值。当我因某种原因在ng-repeat之外引用ng-models时,我得到了正确的值。

我们如何解决这个问题?什么是最简单的解决方案?

2 个答案:

答案 0 :(得分:1)

它应该是这样的。正如我们所知,ng-repeats指令创建了自己的新范围。

  

bday.editing

wp_enqueue_script('bootstrap', get_template_directory_uri().'/assets/javascripts/bootstrap.min.js', array('jquery'),'v3',true);

这里我从您的问题中理解的是,您只想编辑您点击的项目。这是同样的解决方案。 针对同一问题的另一个解决方案是创建一个新函数,该函数采用一个“bday”参数。仅对此项目进行编辑true,并为所有其他元素设置编辑false。如果用户没有提交表单并单击其他项目,则此解决方案适用于该情况。

答案 1 :(得分:1)

问题是该项目属于重复范围。

如果您将ng-model更改为:

<ul ng-repeat="notes in notes">
    <li>
      <span ng-hide="editing" ng-click="editing = true">{{note.name}} | {{note.content}}</span>
      <form ng-show="editing" ng-submit="editing = false">
        <label>Name:</label>
        <input type="text" ng-model="note.name" placeholder="Name" ng-required/>
        <label>Content:</label>
        <input type="date" ng-model="note.content" placeholder="Content" ng-required/>
        <br/>
        <button class="btn" ng-click="edit(note)">Save</button>
      </form>
    </li>
</ul>

现在note.name / note.content

然后,不是将note.id填充到编辑按钮,而是传递整个note,即ng-click="edit(note)"

然后你的控制器将通过整个音符。

$scope.edit = function (note) {    
    // send note to server via $http, changes to `note` are already made directly to the note itself
};

希望这是有道理的。