这里发生的情况是,在ui中启用了一些菜单项,而禁用了一些菜单项。因此,当用户单击被禁用的菜单项时,它会在页面上显示错误。
我尝试使用angularjs-service和$broadcast来解决这个问题。现在的问题是,因为每个页面,包括左侧菜单,都有不同的控制器,所以我需要将$broadcast数据重复到每个控制器。我所期待的就是如何删除这种冗余?
Left-Menu-Service.js
'use strict';
angular.module("MainApp")
.factory('menuClick', function($rootScope) {
var sharedService = {};
sharedService.notify = {};
sharedService.prepForBroadcast = function(msg) {
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});Left-Menu-Controller.js
'use strict';
angular.module("MainApp")
.controller('LeftMenuCtrl', function ($scope, $rootScope, menuClick) {
$scope.handleMenuClick = function(action) {
menuClick.notify.warningNotify = true;
menuClick.notify.errorNotify = true;
menuClick.notify.successNotify = true;
if(!action.IsEnabled)
{
menuClick.notify.warningNotify = false;
menuClick.notify.warningMessage = "This operation is disabled ( "+action.Text+" )";
menuClick.prepForBroadcast(menuClick.notify);
}
};
});Left-Menu.html
<li>
<a ng-click="handleMenuClick(submenu)">{{submenu.Text}}</a>
</li>Notification-Directive.js
'use strict';
angular.module("MainApp")
.directive('notification', function () {
return {
restrict: 'E',
templateUrl: function (tElement, tAttrs) {
if (tAttrs.type) {
switch (tAttrs.type){
case 'error':
return 'partials/template/show_error.html';
break;
case 'success':
return 'partials/template/show_success.html';
break;
case 'warning':
return 'partials/template/show_warning.html';
break;
}
}
}
};
});show_error.html
<div ng-hide="notify.errorNotify" ng-init="notify.errorNotify=true">
<button type="button" ng-click="notify.errorNotify = !notify.errorNotify"></button>
<h2>{{notify.errorMessage}}</h2>
</div>Controller-of-the-all-the-pages-where-this-directive-is-used.js
$scope.$on('handleBroadcast', function() {
$scope.notify = menuClick.notify;
});我不知道如何修补指令本身中的所有内容,以避免在所有控制器中重复上面的代码。谢谢!
发布于 2015-09-19 20:16:15
这可能不是理想的答案,但将帮助您理解如何使用服务共享方法。
将$scope.handleMenuClick的函数声明从控制器移动到您的服务:
.factory('menuClick', function($rootScope) {
var sharedService = {};
sharedService.notify = {};
// new function
sharedService.handleMenuClick = function(action) {
sharedService.notify.warningNotify = true;
.......
if(!action.IsEnabled)
.......
}
.....
return sharedService
})然后在控制器中,你只需要引用服务中的方法:
$scope.handleMenuClick = menuClick.handleMenuClick; https://stackoverflow.com/questions/32667916
复制相似问题