问题
So I am working on a new site in AngularJS, and loving it!
I have encountered a problem, however. I am trying to add a jQuery plugin called 'Redactor' to my textareas, but I think what is happening is when I initialise the plugin, it replaces the textarea element. The reason this is problematic, is because I have set an 'ng-model' attribute to the text area, like so:
I am using AngularJS UI to pickup the focus event, and then execute the following code upon focus of the text
$scope.addRedactor = function() {
$('.redactor').redactor();
});
Now I can't seem to get the value of the textarea, because when I try and access the ng-model 'response', it comes up as undefined.
Is there a way I can bind an ng-model attribute to the textarea AFTER it has been affected by Redactor? Else, is there another way I should be getting the textarea's value?
回答1:
I was looking for the same answer today and made a directive to solve it:
angular.module('Module', []).directive("redactor", function() {
return {
require: '?ngModel',
link: function($scope, elem, attrs, controller) {
controller.$render = function() {
elem.redactor({
keyupCallback: function() {
$scope.$apply(controller.$setViewValue(elem.getCode()));
},
execCommandCallback: function() {
$scope.$apply(controller.$setViewValue(elem.getCode()));
}
});
elem.setCode(controller.$viewValue);
};
}
};
});
Then you can just use the following HTML:
<textarea ng-model="yourModel" redactor></textarea>
The model will be updated on each keyUp and whenever the user clicks on a button in the toolbar. The model will contain the HTML code.
I have just started out with AngularJS so please let me know if there are better ways to do this or if I broke some conventions I am still unaware of.
回答2:
For those who find the accepted answer not working as I did. This is the working one (with Angular v1.1.5)
angular.module('Module', []).directive("redactor", function() {
return {
require: '?ngModel',
link: function($scope, elem, attrs, controller) {
controller.$render = function() {
elem = $(elem);
elem.val(controller.$viewValue);
elem.redactor({
changeCallback: function() {
$scope.$apply(controller.$setViewValue(elem.val()));
}
});
};
}
};
});
The changeCallback is way too much better than other callbacks combined and in my case, I have to cast the elem to a Jquery element. I also found that the setCode and getCode is not available at all. May be it is a different version.
回答3:
Use this AngularJS module for "RedactorJS": https://github.com/TylerGarlick/angular-redactor
It worked fine for me.
来源:https://stackoverflow.com/questions/15470721/angularjs-redactor-plugin