Angular 服务应该操纵 DOM 吗?
Should Angular Services Manipulate the DOM?
所以据我了解,让服务操纵 DOM 是不好的做法。 DOM 操作应保留给指令。我想创建类似于模式的东西,其中调用服务以生成 DOM 元素。
e.i.
function MyController($sope, myModal) {
// Submit a form
$scope.submit = function() {
if (formIsValid) {
// do stuff
} else {
myModal.show({
templateUrl: 'sometemplate.html',
controller: 'MyModalController'
}).then(function() {
// do stuff
});
}
}
}
试图想出不同的方法来做到这一点,看起来最简单的方法是让服务在页面中注入一个 DOM 元素-
function MyModalService($http, $compile, $controller, $rootScope) {
this.show = function (options) {
var $scope = $rootScope.$new(true);
$controller(options.controller, {
$scope: $scope
});
$http.get(options).success(function(html) {
var ele = $compile(html)($scope);
// Bad practice? Alternatives?
angular.element('body').append(ele);
});
}
}
这可能看起来像小土豆,但我喜欢坚持一种模式,我喜欢打破模式或修改模式的理由。这是常见的还是有更好的方法来做到这一点?
这听起来与 angular-bootstrap 对其模态所做的非常相似。
您可以在此处查看它们的实现:https://github.com/angular-ui/bootstrap/blob/master/src/modal/modal.js(参见第 452 行)
所以据我了解,让服务操纵 DOM 是不好的做法。 DOM 操作应保留给指令。我想创建类似于模式的东西,其中调用服务以生成 DOM 元素。
e.i.
function MyController($sope, myModal) {
// Submit a form
$scope.submit = function() {
if (formIsValid) {
// do stuff
} else {
myModal.show({
templateUrl: 'sometemplate.html',
controller: 'MyModalController'
}).then(function() {
// do stuff
});
}
}
}
试图想出不同的方法来做到这一点,看起来最简单的方法是让服务在页面中注入一个 DOM 元素-
function MyModalService($http, $compile, $controller, $rootScope) {
this.show = function (options) {
var $scope = $rootScope.$new(true);
$controller(options.controller, {
$scope: $scope
});
$http.get(options).success(function(html) {
var ele = $compile(html)($scope);
// Bad practice? Alternatives?
angular.element('body').append(ele);
});
}
}
这可能看起来像小土豆,但我喜欢坚持一种模式,我喜欢打破模式或修改模式的理由。这是常见的还是有更好的方法来做到这一点?
这听起来与 angular-bootstrap 对其模态所做的非常相似。
您可以在此处查看它们的实现:https://github.com/angular-ui/bootstrap/blob/master/src/modal/modal.js(参见第 452 行)