如何在angularjs中与新元素一起使用$compile
我正在尝试用angularjs和bootstrap开发一个友好的对话框插件 我发现基于in指令的对话框不太容易使用,首先添加一个html标记并定义控制器和变量,这太复杂了 所以我打算向angular添加一个方法,创建新元素dynamic并将变量设置为根范围,但在编译方面似乎存在一些问题 主要代码如下:如何在angularjs中与新元素一起使用$compile,angularjs,twitter-bootstrap,Angularjs,Twitter Bootstrap,我正在尝试用angularjs和bootstrap开发一个友好的对话框插件 我发现基于in指令的对话框不太容易使用,首先添加一个html标记并定义控制器和变量,这太复杂了 所以我打算向angular添加一个方法,创建新元素dynamic并将变量设置为根范围,但在编译方面似乎存在一些问题 主要代码如下: var defaultOption = { title: 'Title', content: 'Content', backdrop: false, buttons
var defaultOption = {
title: 'Title',
content: 'Content',
backdrop: false,
buttons: [],
$dom: null
};
var prefix = '__dialog',
index = 0;
var newId = function (scope) {
var id = prefix + index;
if (!scope[id]) return id;
index++;
return arguments.callee(scope);
};
var app = angular.module("app", []);
app.directive('bootstrapModal', ['$compile', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: {
bootstrapModal: '='
},
link: function (scope, $ele) {
var $dom = $(defaultTemplate),
body = $ele.children();
if (body.length) $dom.find('.modal-body').html(body);
$ele.replaceWith($dom);
$compile($dom)(scope);
scope.bootstrapModal.$dom = $dom;
}
};
}]);
angular.ui = {};
angular.ui.dialog = function (args) {
var $body = angular.element(document.body),
$rootScope = $body.scope().$root,
option = $.extend({}, defaultOption, args);
option.id = option.id || newId($rootScope);
option.show = function () {
this.$dom.modal('show');
};
option.hide = function () {
this.$dom.modal('hide');
};
$body.injector().invoke(function ($compile) {
$rootScope[option.id] = option;
var dialog = '<div bootstrap-modal="{0}"></<div>'.format(option.id);
var html = $compile(dialog)($rootScope);
$('body').append(html);
});
return option;
};
$(function () {
angular.ui.dialog({ //test
title: 'Alert',
content: 'test content for alert',
buttons: [{
name: 'Close',
focus: true
}]
}).show();
});
var defaultOption={
标题:“标题”,
内容:“内容”,
背景:错,
按钮:[],
$dom:null
};
变量前缀=“\uuuu对话框”,
指数=0;
var newId=函数(范围){
var id=前缀+索引;
如果(!scope[id])返回id;
索引++;
返回参数。被调用方(作用域);
};
var-app=angular.module(“app”,[]);
指令('bootstrapModal',['$compile',函数($compile){
返回{
限制:“A”,
替换:正确,
范围:{
bootstrapModal:“=”
},
链接:功能(范围$ele){
var$dom=$(defaultTemplate),
body=$ele.children();
if(body.length)$dom.find('.modal body').html(body);
$ele.replaceWith($dom);
$compile($dom)(范围);
scope.bootstrapModal.$dom=$dom;
}
};
}]);
angular.ui={};
angular.ui.dialog=函数(args){
var$body=angular.element(document.body),
$rootScope=$body.scope().$root,
option=$.extend({},defaultOption,args);
option.id=option.id | | newId($rootScope);
option.show=函数(){
这个.$dom.modal('show');
};
option.hide=函数(){
这是.dom.modal('hide');
};
$body.injector().invoke(函数($compile){
$rootScope[option.id]=选项;
var dialog='在代码周围放置一个$rootScope.$apply(function(){…})
,在injector()中编译对话框。invoke(…)
a打字错误:app.directive('bootstrapModal',['$compile',function($complie)@alou已更正,谢谢。:D