【发布时间】: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