[英]How to properly handle popups (modals) in AngularJS app without bootstrap
I have few popups in my application. 我的应用程序中没有几个弹出窗口。 One is for displaying "About" and the second one for displaying contact form.
一种用于显示“关于”,另一种用于显示联系方式。 What I do currently is I put the whole popup DOM into template and write custom directive like this:
我目前要做的是将整个弹出式DOM放入模板中,并编写如下的自定义指令:
angular.module('app').directive('contactForm', function() {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: 'contactForm.html',
controller: function($scope) {
$scope.submitForm = function() {
...
}
},
link: function(scope, el) {
scope.$on('openContactForm', function() {
el.show();
});
}
}
});
and call such directive somewhere in my index.html 并在我的index.html中的某处调用这样的指令
<body>
<about-popup></about-popup>
<contact-form></contact-form>
...
...
</body>
Somewhere on the page there is controller like this with function bound to button: 页面上的某处有这样的控制器,其功能绑定到按钮:
angular.module('app').controller('SideBarController', function($scope, $rootScope) {
$scope.openContactForm = function() {
$rootScope.$broadcast('openContactForm');
}
});
I don't feel that's the best way of handling that, but can't figure out how to do this better. 我认为这不是处理此问题的最佳方法,但无法弄清楚如何更好地做到这一点。 Do you have any ideas, examples?
您有什么想法和例子吗?
The last app I did needed a simple modal to display messages and the way I did was with a directive very similar to yours. 我做的最后一个应用程序需要一个简单的模式来显示消息,而我做的方式是使用与您的指令非常相似的指令。
The directive appends the template and uses the $rootScope to store a modal object, this object has the attribute show (used by the ng-show in the template) and the toggle function that is called every time I need to show/hide the modal window. 该指令附加模板并使用$ rootScope来存储模态对象,此对象具有show属性(由模板中的ng-show使用)和每次我需要显示/隐藏模态时都会调用的toggle函数窗口。 Because the object is in the $rootScope you can use it from anywhere.
由于该对象位于$ rootScope中,因此您可以在任何地方使用它。
Here is a simplified version of that directive. 这是该指令的简化版本。
app.directive('myModal', ['$rootScope', function ($rootScope) {
return {
restric: 'A',
replace: true,
template: '<div class="modal" ng-show="modal.show">{{ modal.mainMessage }}<br /><button ng-click="modal.toggle()">Close</button></div>',
link: function (scope, elm, attrs) {
$rootScope.modal= {
mainMessage: '',
show: false,
toggle: function (mainMessage) {
this.mainMessage = mainMessage;
this.show = !this.show;
}
};
}
};
}]);
This is a good question, I am curious about the answers it will get. 这是一个很好的问题,我很好奇它将获得的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.