【问题标题】:angularJS one way data binding and model edit with ng-repeatangularJS 单向数据绑定和模型编辑与 ng-repeat
【发布时间】:2015-02-17 13:59:57
【问题描述】:

在我的应用程序中,我使用模态表单来编辑表格视图数据。我有一个麻烦,在第一步我没有使用其他变量和 .copy() - 所以当我编辑我的数据时 - 在表中我没有看到任何编辑,直到我点击保存(所以现在它是参考)。现在我需要做我之前描述过的事情......

我看到 angularJS 1.3 添加了一项功能:单向数据绑定。

我可以在我的应用程序中以某种方式使用它吗?

我写了一个plunker:

http://plnkr.co/edit/4gAWiK5gVg58jWtwYovK?p=preview

和代码:

<html ng-app="myapp">
  <head>
    <script data-require="angular.js@1.4.0-beta.4" data-semver="1.4.0-beta.4" src="https://code.angularjs.org/1.4.0-beta.4/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-controller="ArticleCtrl">
    <h1>Hello Plunker!</h1>
    <ol >
      <li ng-repeat="item in articles">
        <h4>{{item.name}}</h4>
        <h2>{{::item.age}}</h2> <!--(like this i wanna to use with angularJS 1.3)-->
        <a ng-click="editArticle(item)"> - Edit - </a>
      </li>
    </ol>
    Edit your title: <input type="text" ng-model="article.name"/>
    Edit your age: <input type="text" ng-model="article.age"/>
    <p>And save:</p>
    <button type="submit">Save</button>
  </body>
</html>

和js:

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

angular.module('myapp')
  .controller('ArticleCtrl', ['$scope', function($scope) {
    $scope.articles = [{name: '123', age: 10}, {name: '456', age: 20}, {name: '789', age: 30}];
    $scope.article = {name: '', age: ''};
    $scope.editArticle = function(article){
      $scope.article = article;
    };
  }])

如果有不清楚的地方,请写在 cmets 中。谢谢。

还有一次很快:在单击“保存”按钮之前不要更新 ng-repeat 中的模型。

【问题讨论】:

  • 您是说您不想使用 .copy() 方法来延迟应用模型更改吗?您不能使用一种方式数据绑定来执行您所描述的操作。这仅用于将数据填充到 dom 中一次,然后再也不会更改它。复制您的模型对象是执行您所描述的操作的唯一方法。
  • @jw56578 是的 - 有了副本,我几乎需要从零重写代码......另外:也许在更新一项后可以更改 ng-repeat 数组项?

标签: javascript jquery html angularjs


【解决方案1】:

不确定您是否已经找到解决问题的方法。

根据 cmets 中的建议,您需要复制模型对象并在保存时将新数据重新应用于模型。

这是我通过以下更改找到的解决方案:

$scope.editArticle = function(article){
      edit_article = article; // edit_article stores a reference to the article to edit
      angular.copy(article, $scope.article); // copy article to form fields --> ref. by $scope.article
};
$scope.saveArticle = function(){
      update(edit_article, $scope.article); // dest. is stored reference to element in list
                                            // source is the new input
      //console.log('edited value', $scope.article);
};

简短说明:我将文章的引用存储在 edit_article 中,因为 angular.copy 正在从副本中删除 $$hashKey 并且 angular 无法在没有哈希的数组。 单击保存后,更新功能会将保存的文章更改为新输入的数据。

我找到了一个有用的blog post,我从中获取了更新功能。

您可以找到更新的 plunkr here。

【讨论】:

  • 你的答案很好,但在我的情况下很难改变:有很多逻辑......
  • 表格中的更新有些不清楚...如何更新表格中的值?
  • 表是什么意思?您是指 ng-repeat 中使用的值吗?请在演示 jsfiddle 中显示更多代码,我可以尝试提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2017-11-24
  • 2016-10-31
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多