0

我有我的範圍數組,我遍歷每個元件都在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]是不確定的,我不知道如何讓模型或元素的引用,被改變。

任何想法?感謝幫助。

回答

1

不應在任何循環中使用$watch。在這種情況下,您可以使用ng-change而不是$watch。並在ng-change函數中發送​​。像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; 
    }); 
0

我建議使用ngChange來代替。

你可以做這樣的事情:

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

,並添加控制器內的功能。如果你需要知道,改變了你可以使用$指數從NG重複知道元素的索引,其中是更改過的數據:

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

$scope.somethingChanged = function(index) { 
    $scope.articles[index]; <--------- Here is the element that changed 
} 

編碼愉快!