我正在使用contenteditable属性更新电话列表中的电话名称。我已经尝试使用ng-change,但是多数民众赞成在没有被解雇。有什么办法可以做到吗?
我有一个Store.Phones
列表
<ul class="store">
<li ng-repeat="Phone in Store.Phones">
<strong contenteditable> {{Phone.Name}}</strong>
</li>
<ul>
因此,现在当我编辑电话名称时,我需要在列表中对其进行更新。
我已经尝试过使用指向该元素的模型进行类似的操作。这是行不通的。
<strong ng-model='Store.Phones[$index].Name'> {{Phone.Name}}</strong>
还
<strong ng-model='PhoneName' ng-change='PhoneNameChanged()'> {{Phone.Name}}</strong>
但在这种情况下,该方法不会被触发。
最佳答案
编辑
这是一个基于Angular文档中示例的示例,该示例仅使用ng-repeat
。由于ng-repeat
为每次迭代创建新的作用域,所以这不是问题。
<!doctype html>
<html ng-app="form-example2">
<head>
<script src="http://code.angularjs.org/1.0.5/angular.min.js"></script>
<script>
angular.module('form-example2', []).directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
// view -> model
elm.bind('blur', function() {
scope.$apply(function() {
ctrl.$setViewValue(elm.html());
});
});
// model -> view
ctrl.$render = function() {
elm.html(ctrl.$viewValue);
};
// load init value from DOM
ctrl.$setViewValue(elm.html());
}
};
});
</script>
</head>
<body>
<div ng-repeat="i in [1, 2, 3]">
<div contentEditable="true" ng-model="content" title="Click to edit">Some</div>
<pre>model = {{content}}</pre>
</div>
<style type="text/css">
div[contentEditable] {
cursor: pointer;
background-color: #D0D0D0;
}
</style>
</body>
</html>
原来的
这里有一个示例,您可以做到这一点:http://docs.angularjs.org/guide/forms
它在“实现自定义表单控件(使用ngModel)”标题下。