我正在大量修改 WYSIWYG js 插件,并将我自己的自定义元素插入其中。 为了插入自定义元素,我使用了指令,以便在需要进行更改时可以轻松维护它们。到目前为止,这是我的代码示例:
所见即所得编辑器的初始加载:
<div ng-controller="wyswiygCtrl">
<textarea wysiwyg-editor ng-model="content"></textarea>
</div>
这是我插入到所见即所得内容中的自定义元素(指令)的示例:
<wysiwyg-element class="custom_element" name="awesome" type="checkbox" checked="true"></wysiwyg-element>
我在指令的初始化中使用以下代码来编译其中的任何自定义元素(指令):
var e = angular.element(wysiwygEditor.get(0).innerHTML);
$compile(e.contents())(scope);
wysiwygEditor.html(e);
它按照我的需要编译指令,但棘手的部分来了。我需要能够从外部 Angular 调用“wysiwygCtrl”中的函数。我可以在编译之前执行此操作,但由于某种原因,在使用 angular 的编译功能后,我无法访问元素的范围。
这是在 $compile
之前运行的代码:
angular.element($('.custom_element')).scope().wysiwygModal();
angular.element($('.custom_element')).scope().$apply();
在 $compile 之后尝试调用 wysiwygModal
函数后出现以下错误:
Uncaught TypeError: Object #<Object> has no method 'wysiwygModal'
我做错了什么?
最佳答案
我能够访问编译元素上的 scope()
及其变量。如果这没有帮助,您可以编辑此插件或创建您自己的插件吗?
http://plnkr.co/edit/kvbvKXeVjEhmeE7257ly?p=preview
script.js
var myApp = angular.module('myApp', []);
myApp.directive('myEditor', function () {
return {
restrict: 'E',
scope: {
},
template:
'<div>' +
'<h3>Raw HTML</h3>' +
'<textarea rows=5 cols=40 ng-model="text"></textarea>' +
'</div>' +
'<hr />' +
'<div>' +
'<h3>Compiled HTML</h3>' +
'<div my-preview></div>' +
'</div>' +
'<hr />' +
'<div>' +
'<h3>Messages generated during compilation</h3>' +
'<div ng-repeat="message in messages">[{{message}}]</div>' +
'</div>' +
'</div>',
controller: function ($scope) {
$scope.messages = [];
this.getText = function () {
return $scope.text;
};
this.addMessage = function (message) {
$scope.messages.push(message);
};
this.clearMessages = function () {
$scope.messages.length = 0;
};
},
link: function (scope, element, attrs) {
scope.text = '<div ng-init="a = 2" class="my-selector">\n scope.a : [{{a}}]\n</div>';
}
};
});
myApp.directive('myPreview', function ($compile) {
return {
require: '^myEditor',
link: function (scope, element, attrs, myEditorController) {
scope.$watch(myEditorController.getText, function (newValue) {
if (newValue !== undefined) {
var e = angular.element('<div>' + newValue + '</div>');
$compile(e)(scope);
element.html(e);
myEditorController.addMessage(
'The value of "a" on the scope of the compiled element is: ' +
angular.element($('.my-selector')).scope().a)
}
});
}
};
});
index.html
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="angular.js@*" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp">
<my-editor></my-editor>
</div>
</body>
</html>
关于javascript - Angular - 编译指令后无法访问 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19675027/