问题
I have a contenteditable div like this:
<div contenteditable="true" ng-model="name">{{ name }}</div>
<input type="button" ng-click="checkScope()" value="Click me">
In my controller:
var app = angular.module('sbAdminApp', []);
app.controller('MyCtrl', function($scope) {
$scope.name = 'Adrian';
$scope.checkScope = function(){
console.log($scope.name);
}
});
How can I get the latest value of contenteditable div using scope when I click the button?
回答1:
you need a directive to work this
app.directive('contenteditable', [function() {
return {
require: '?ngModel',
scope: {
},
link: function(scope, element, attrs, ctrl) {
// view -> model (when div gets blur update the view value of the model)
element.bind('blur', function() {
scope.$apply(function() {
ctrl.$setViewValue(element.html());
});
});
// model -> view
ctrl.$render = function() {
element.html(ctrl.$viewValue);
};
// load init value from DOM
ctrl.$render();
// remove the attached events to element when destroying the scope
scope.$on('$destroy', function() {
element.unbind('blur');
element.unbind('paste');
element.unbind('focus');
});
}
};
}]);
and you can use it like this
<div contenteditable="true" ng-model="name">{{ name }}</div>
here is a demo
来源:https://stackoverflow.com/questions/32816942/get-contenteditable-div-value-in-angular