Angularjs Ng控制器与Ng repeat位于同一元素上-无双向数据绑定
我无法让双向数据绑定在角度重复中工作。 我在指定了ng repeat的同一元素上指定了ng控制器- 我刚刚了解到,通过这样做,我可以通过ng repeat获得正在迭代的每个项目。以下是HTML:Angularjs Ng控制器与Ng repeat位于同一元素上-无双向数据绑定,angularjs,Angularjs,我无法让双向数据绑定在角度重复中工作。 我在指定了ng repeat的同一元素上指定了ng控制器- 我刚刚了解到,通过这样做,我可以通过ng repeat获得正在迭代的每个项目。以下是HTML: <div ng-controller="OtherController"> <div id="hoverMe" ng-controller="ItemController" ng-mouseenter="addCaption()" ng-mouseleave="saveC
<div ng-controller="OtherController">
<div id="hoverMe" ng-controller="ItemController" ng-mouseenter="addCaption()"
ng-mouseleave="saveCaption()" ng-repeat="image in images">
<div class="imgMarker" style="{{image.css}}">
<div ng-show="image.captionExists" class="carousel-caption">
<p class="lead" contenteditable="true">{{image.caption}}</p>
</div>
</div>
</div>
</div>
以及其他控制器:
function ItemController($scope){
$scope.addCaption = function(){
if($scope.image.captionExists === false){
$scope.image.captionExists = true;
}
}
$scope.saveCaption = function(){
console.log($scope.image.caption);
}
}
function OtherController($scope){
$scope.images = ..
}
当我将鼠标悬停在#hover me div上时,正确添加了caption div。但是,当我在段落中输入一些文本,然后将鼠标移离#hoveMe div时,$scope.image-variables标题值不会在saveCaption方法中更新。我知道我遗漏了什么。但是它是什么?我假设您正在编辑
p
contenteditable中的内容,并且希望模型图像。标题
更新。要使其工作,您需要设置双向绑定
支持ng模型的元素可以使用双向绑定,否则需要手动同步数据。检查
ngModelController
和此处提供的示例。它应该满足您的需要。您不需要在具有ng repeat的同一元素上指定ng控制器来获取每个项目
您可以获得如下项目:
<div ng-repeat="image in images" ng-mouseenter="addCaption(image)" ng-mouseleave="saveCaption(image)" class="image">
要使contenteditable
正常工作,您需要使用ng model
和正确更新模型的指令
以下是一个简单的示例,基于:
请注意,该指令可能需要更多的逻辑才能处理例如换行
这是一个有效的插件:您能提供一个JSFIDLE吗?
$scope.addCaption = function (image) {
if(!image.captionExists){
image.captionExists = true;
}
};
app.directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, controller) {
element.on('blur', function() {
scope.$apply(function() {
controller.$setViewValue(element.html());
});
});
controller.$render = function(value) {
element.html(value);
};
}
};
});