好吧,我想创建一个“summernote”指令(wysiwyg编辑器)。
这是模板:
<summernote active="false">
<button class="edit" ng-click="edit()">Edit</button>
<button class="save" ng-click="saveData()">Save</button>
<button class="cancel" ng-click="cancel()">Cancel</button>
<div class="summernote"></div> // here will be loaded the summernote script
</summernote>
指令代码:
...
.directive('summernote', function($compile) {
return {
restrict: 'E',
replace: true, // Not sure about what this code does,
scope: {
active: '='
},
link: function($scope, elem, attrs) {
var $summernote = elem.find('.summernote'),
$edit = elem.find('.edit'),
$save = elem.find('.save'),
$cancel = elem.find('.cancel');
$scope.active = false;
$scope.$watch('active', function(active) {
// switch summernote's & buttons' state
// code ...
});
// here I have the buttons' click event defined
// QUESTION 1: Is there a better way?
// I'm doing this because the code below is not working.
$edit.on('click', function() {...});
$cancel.on('click', function() {...});
$save.on('click', function() {...});
// THIS IS NOT WORKING...
$scope.edit = function() {
alert('edit');
};
$scope.cancel = function() {
alert('cancel');
};
}
}
});
当我点击保存按钮时,我想发送一些数据,所以我在mainController上声明了saveData,但是我必须发送div.summernote数据,我不知道该怎么做
<button class="save" ng-click="saveData(getSummernoteDataFromDirectiveScope?)">Save</button>
MainController:
.controller('MainController', function($scope, myDataFactory) {
$scope.saveSummernoteData(data) {
myDataFactory.updateData('field_name', data);
}
}
主要问题是,如何使用不同的?范围。问题是我要分离指令逻辑(编辑,取消,div.summernote行为)和“保存”按钮,其逻辑在MainController中声明(或主$ scope,这是我的混乱)。 / p>
链接函数的$ scope和MainController $ scope是否相同??
我想我对所有这些都有点麻烦,所以任何帮助(文档)都会受到赞赏。
答案 0 :(得分:1)
可在此处directives和此处compile找到文档。
替换:true,会将您附加指令的元素替换为您的模板,因为在您的情况下,您的模板似乎与您不需要的代码内联(也将在下一个主要内容中删除)释放角度。)
问题1:您不需要在事件上绑定$ ng-click应该正常工作。
如果要在控制器中定义保存功能,可以将函数作为属性传递,并在指令中定义的保存例程中调用它:
在你的HTML中:
<summernote active="false" on-save="saveData()">
<button class="edit" ng-click="edit()">Edit</button>
<button class="save" ng-click="save()">Save</button>
<button class="cancel" ng-click="cancel()">Cancel</button>
<div class="summernote"></div> // here will be loaded the summernote script
</summernote>
在您的指令中:
scope: {
active: '=',
invokeOnSave: '&onSave'
},
link: function($scope, elem, attrs) {
...
$scope.save = function() {
var data = "some data"; //Whatever mechanism you use to extract the data from your div
$scope.invokeOnSave(data);
};
...
}