【问题标题】:Update model in ng-repeat when is self-updated自我更新时更新 ng-repeat 中的模型
【发布时间】:2016-05-14 05:28:42
【问题描述】:

我的作用域中有一个数组,我正在使用 html 模板中的输入迭代每个元素:

控制器:

    app.controller("otherArticleCtrl", ["$scope", "$http", function($scope, $http) {

        $scope.articles = [{ url: 'index.php', title: "First"}, { url: 'index.php', title: "Second"}];
    }]);

模板:

<div ng-repeat="(key, article) in articles track by $index">
  <h1>{{ article.title }}</h1>
  <input type="text" ng-model="article.url"/>
</div>

当用户修改输入中的 url 时,我需要进行 AJAX get 调用,并更新文章标题。

我创建了一个循环遍历数组的 watch 函数:

for(var i=0; i < $scope.articles.length; i++) {
    $scope.$watch('articles['+i+'].url', function(new, old){
       if(new != old){
           $http({
               method: 'GET',
               url: new
           }).then(function successCallback(response) {
               $scope.articles[i].title = response.title;
           });
       }
    }, true);
}

但是 $scope.articles[i] 是未定义的,我不知道如何获取更改的模型或元素的引用。

有什么想法吗?感谢您的帮助。

【问题讨论】:

    标签: javascript angularjs angularjs-scope angularjs-ng-repeat watch


    【解决方案1】:

    我建议改用ngChange

    你可以这样做:

    <input type="text" ng-model="article.url" ng-change="somethingChanged()"/>
    

    并在控制器中添加该功能。如果您需要知道更改的元素的索引,您可以使用 ng-repeat 中的 $index 来了解更改的数据在哪里:

        <input type="text" ng-model="article.url" ng-change="somethingChanged($index)"/>
    
    $scope.somethingChanged = function(index) {
       $scope.articles[index];   <--------- Here is the element that changed
    }
    

    编码愉快!

    【讨论】:

      【解决方案2】:

      不应在任何循环中使用$watch。在这种情况下,您可以使用ng-change 而不是$watch。并在ng-change 函数中发送index number。喜欢ng-change="changeUrl($index)"。和功能如下图。

      可以试试:

      在 html 中:

      <div ng-repeat="(key, article) in articles track by $index">
        <h1>{{ article.title }}</h1>
        <input type="text" ng-model="article.url" ng-change="changeUrl($index)"/>
      </div>{{index}}
      

      在控制器中:

      $scope.articles = [{ url: 'index.php', title: "First"}, { url: 'index.php', title: "Second"}];
      
        $scope.changeUrl =  function(index){
        $http({
                  method: 'GET',
                  url: $scope.articles[index].url
              }).then(function successCallback(response) {
                  $scope.articles[index].title = response.title;
              });
        };
      

      你可以使用$http.get

      $http.get($scope.articles[index].url)
          .then(function(response) {
              $scope.articles[index].title = response.title;
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-06
        • 1970-01-01
        • 1970-01-01
        • 2014-04-24
        相关资源
        最近更新 更多