鉴于以下服务旨在创建“对话框”元素(即模态):
app.service('dialog', ['$document', '$compile', '$rootScope',
function($document, $compile, $rootScope) {
var body = $document.find('body');
var scope = $rootScope.$new();
this.createDialog = function() {
var dialogElem = angular.element('<div ng-include="\'/dialog.html\'"></div>');
$compile(dialogElem)(scope);
body.append(dialogElem);
};
}
]);
可以在控制器中使用,如下所示:
$scope.someFunction = function() {
dialog.createDialog();
};
我可以使用$compile
或其他任何方式在我的服务中不使用HTML吗?我真的更喜欢只调用一个指令,因此运行createDialog()
会立即将指令注入我的DOM,因此该指令负责将新控制器和模板链接在一起。如果我以错误的方式解决这个问题,我会对建设性的想法持开放态度。
答案 0 :(得分:13)
当然你可以!,你走了:
app.factory('modalService', function ($document, $compile, $rootScope, $templateCache, $http) {
var body = $document.find('body'),
modals = [];
var service = {
show: function (template, data, modal) {
// The template's url
var url = 'template/modal/' + template + '.html';
// A new scope for the modal using the passed data
var scope = $rootScope.$new();
angular.extend(scope, data);
// Wrapping the template with some extra markup
modal = modal || angular.element('<div class="modal"/>');
// The modal api
var api = {
close: function () {
modal.remove();
scope.$destroy();
modals.splice(modals.indexOf(api), 1);
},
replace: function (template, data) {
return angular.extend(api, service.show(template, data, modal));
}
};
// Adding the modal to the body
body.append(modal);
// A close method
scope.close = api.close;
// Caching the template for future calls
$http.get(url, {cache: $templateCache})
.then(function (response) {
// Wrapping the template with some extra markup
modal.html('<div class="win">' + response.data + '</div>');
// The important part
$compile(modal)(scope);
});
modals.push(modal);
return api;
},
showOrReplaceLast: function (template, data) {
return service.show(template, data, modals.length > 0 ? modals[modals.length - 1] : null);
}
};
return service;
});
一些注意事项:
答案 1 :(得分:1)
你可以尝试如下,只是在打开对话框之前渲染你的ng-include
app.service('dialog', ['$http', '$compile', '$q', '$templateCache'
function($http, $compile, $q, $templateCache) {
this.compileInclude = function(scope, url) {
var deferred = $q.defer();
$http.get(url, {cache : $templateCache}).then(function(response){
deferred.resolve($compile(response.data)(scope));
});
return deferred.promise;
};
}
]);
从控制器写如下
dialog.compileInclude($scope, 'dialog.html').then(function(){
// open dialog here
});