angularJS单向数据绑定和模型编辑与ng重复



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

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

我可以在我的应用程序中使用它吗?

我写了一篇博文:

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;
    };
  }])

如果有什么不清楚的地方,请写在评论里。非常感谢。

还有一次,很快:在点击"保存"按钮之前,不要重复更新模型。

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

根据注释中的建议,您需要复制模型对象,保存时可以将新数据重新应用于模型。

这是我发现的具有以下更改的解决方案:

$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无法在没有哈希的数组中定位位置。单击保存后,更新功能会将保存的文章更改为新输入的数据。

我发现了一篇有用的博客文章,我从中获得了更新功能。

你可以在这里找到更新的plunkr。

最新更新