为了能够观察contenteditable
div或input
元素的内容更改,我创建了以下指令:
app.directive('contenteditable',function() { return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
// view -> model
element.bind('input', function() {
scope.$apply(function() {
ctrl.$setViewValue(element["0"].tagName=="INPUT" ? element.val() : element.text());
scope.watchCallback(element.attr('data-ng-model'));
});
});
// model -> view
ctrl.$render = function() {
element.text(ctrl.$viewValue);
element.val(ctrl.$viewValue);
};
}};
});
我的测试控制器看起来像:
function TestController($scope) {
$scope.singleVal = "X";
$scope.multiVal = ["A"];
$scope.addRow = function() {
$scope.multiVal.push("");
};
$scope.watchCallback = function(modelName) {
console.log(modelName+" was changed");
};
}
当我针对以下html测试它时,singleVal(静态创建)表现良好,但我的multiVal(使用ng-repeat动态创建)不行。当我输入一个值时,它只保留原始值(即模型没有刷新)。请帮忙。
<div data-ng-controller="TestController">
<div contenteditable="true" data-ng-model="singleVal"></div>
<button data-ng-click="addRow()">Add Row</button>
<table data-ng-repeat="val in multiVal"><tr><td>
<div contenteditable="true" data-ng-model="val"></div>
</td></tr></table>
</div>
答案 0 :(得分:3)
您无法将ngModel
直接绑定到数组中的字符串。您需要在multiVal
:
$scope.multiVal = [{property: "A"}];
在此处演示: http://jsfiddle.net/YMJzN/
顺便说一句,您还需要调整$scope.addRow
来做同样的事情......
$scope.addRow = function() {
$scope.multiVal.push({property:'new'});
}