javascript - AngularJS 使用 ng-repeat 进行单向数据绑定(bind)和模型编辑

标签 javascript jquery html angularjs

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

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

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

我写了一个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;
    };
  }])

如有不清楚的地方,请在评论中留言。谢谢。

再一次,很快:不要在 ng-repeat 中更新模型,直到单击“保存”按钮。

最佳答案

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

正如评论中所建议的,您需要复制模型对象,并在保存时可以将新数据重新应用到模型。

这是我发现的解决方案,进行了以下更改:

$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 .

关于javascript - AngularJS 使用 ng-repeat 进行单向数据绑定(bind)和模型编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28563159/

相关文章:

打开 Intranet 网站无法正常工作时,Internet Explorer 11 上的 Javascript window.open()

javascript - 将事件绑定(bind)到 ajax 加载的内容

jquery - <li> 列表在 4 行中具有相同的高度,最大 li 的高度不变?

javascript - 我想让我的 sidenav 从页面推送内容

Javascript - 正则表达式仅捕获前 3 个匹配项

javascript - 切换菜单不工作 JQuery

html - HTML 中伪 3D 的数学帮助

javascript - 自定义指令中的 ng-table 错误 "Cannot set property ' $data' of null"

javascript - 从数组中获取标志值的按位组合值

javascript - jquery中获取类别过滤器颜色的方法