【发布时间】:2016-08-29 12:23:44
【问题描述】:
我在ng-repeat 中使用了一个隔离范围指令,它从该模板的控制器迭代一个数组。模板如下:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="bootstrap.min.css" />
<script src="angular.min.js"></script>
<script src="script1.js"></script>
</head>
<body ng-app="AddNewTest" ng-controller="AddNewController">
<div class="items" ng-repeat="row in rows">
<add-new-row data="row" index="$index"></add-new-row>
</div>
</body>
</html>
指令定义如下:
angular.module('AddNewTest', []).
directive('addNewRow', function ($timeout) {
return {
controller: 'AddNewController',
link: function (scope, element, attribute) {
element.on('keyup', function(event){
if(scope.index + 1 == scope.rows.length) {
console.log('keyup happening');
$timeout(function () {
scope.rows.push({ value: '' });
scope.$apply();
});
}
})
},
restrict: 'E',
replace: true,
scope: {
index: '='
},
template: '<div class="add-new"><input type="text" placeholder="{{index}}" ng-model="value" /></div>'
}
}).
controller('AddNewController', function ($scope, $timeout) {
$scope.rows = [
{ value: '' }
];
});
但即使在添加新行并执行$apply() 之后,ng-repeat 也不会呈现添加的新数据。请帮忙。
【问题讨论】:
-
指令中有隔离范围。在指令中传递
rows的数组。像这样scope: { index: '=', rows:"=" }。不要在控制器AddNewController中创建行。删除$scope.rows = [ { value: '' } ]。 -
您希望它如何工作?每个值的输入?只有 1 个输入用于推入数组?你期待什么结果?
-
@gyc 我想在最后一行的 keyup 事件上添加新行。
标签: javascript angularjs angularjs-directive angularjs-ng-repeat isolate-scope