需求背景:
directive模块化某表单信息,但表单信息可加入多条。此时就涉及到clone directive.
解决方式:
能够通过使用angularjs中$compile来进行clone directive。clone direcitve中常涉及到数据的绑定。
详细方法:
tw.factory('DirectiveUtil', [function() {
var DirectiveUtil = {}; DirectiveUtil.DirectiveBuilder = function(directiveName) { directive = directiveName;
directiveBuffer = '<' + directiveName + ' '; this.setDirectiveName = function(directiveName) {
directive = directiveName;
directiveBuffer = '<' + directiveName + ' ';
} this.getDirectiveName = function() {
return directive;
}
// name: directive中scope的name, value: clone directive操作时,数据绑定的名称
this.appendAttr = function(name, value) {
directiveBuffer += name + '=\'' + value + '\' ';
return this;
} this.build = function(compile, scope) {
return compile(directiveBuffer + ' />')(scope);
}
}; return DirectiveUtil;
}]);
使用方式:
var dirctBuilder = new DirectiveUtil.DirectiveBuilder('tw-contact-form');
dirctBuilder.appendAttr('is-new', 'isNew') // $scope.isNew, $scope.showAddBtn, $scope.initData
.appendAttr('show-add-btn', 'showAddBtn')
.appendAttr('init-data', 'initData'); var li = $('<li></li>').attr('id', 'ContactList' + len);
li.append(dirctBuilder.build($compile, $scope));
注意:引入DirectiveUtil,调用build时传入$compile和$scope。