在自我更新时以ng重复更新模型

Update model in ng-repeat when is self-updated

本文关键字:更新 ng 模型 自我      更新时间:2023-09-26

我的范围内有一个数组,我正在使用 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 获取调用并更新文章标题时,我需要。

我做了一个遍历数组的监视函数:

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]是未定义的,我不知道如何获取已更改模型或元素的引用。

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

不应在任何循环中使用$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;
    });

我建议改用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
}

祝您编码愉快!