[英]Updating angular directive with service
我的目的是從后端提取菜單結構的一部分並將其“注入”到我的菜單中。 這取決於應用程序的狀態(登錄/注銷和用戶權限)。
我建立一個指令:
AppDirectives.directive("menutagebuch", ['MenuStructureService',function(MenuStructureService){
/// get the html from the backend
var getelement = MenuStructureService.get();
var elementtoinsert = angular.element(getelement);
return {
restrict: "A",
template: elementtoinsert,
link: function(scope,element){
// some $scope.$watch to recall MenuStructureService.get(); on $rootscope change
}
}
}]);
我的服務:
AppFactories.factory("MenuStructureService", function($http) {
return {
get: function() {
var getMenuStructure = $http.get('/menustructure').success(function(data){
return data;
});
}
}
});
我遇到的問題是該指令在加載menustructure之前執行了。我該怎么做?還是我使用了錯誤的方法? angularJS的新手。
是的,問題是您是否真的要在此處使用指令。 還是控制器足以滿足您的需求。 如果確實要為此編寫指令,並且要操作DOM元素,則應在編譯步驟中執行此操作。
要做到這一點,Angular風格可以使用一個模板來實現,而不是在編譯步驟中進行jQuery風格的DOM操作。 如果使用模板,則可以在鏈接步驟中訪問服務。
//Service
...
get: function() {
// Rather than handling the success in the service return the promise directly
return $http.get('/menustructure');
}
...
//Directive
...
link: function(scope, element) {
scope.menu = MenuStrucutureService.get();
}
templateUrl: "...template.html"
...
<!-- Example Directive Template -->
<div ng-repeat="item in menu.admin.items">
<span>{{item.name}}</span>
</div>
如果遵循有角度的文檔中的經驗法則,則指令控制器在這里可能沒有意義:“最佳實踐:當您要將API公開給其他指令時使用控制器。否則,請使用鏈接。”
好的,我解決的方法是將所有“動作”移至MenuCtrl並查看身份驗證狀態。 如果身份驗證狀態更改,它將調用工廠MenuStructureService來獲取菜單的元素。 然后,使用ng-show和ng-repeat,我控制顯示/隱藏菜單的動作以及元素的填充。
身份驗證狀態更改:
$rootScope.authstatus = true;
控制器處理動作:
$rootScope.$watch('authstatus',function(){
MenuStructureService.get();
});
$rootScope.$on('menustructure', function(event){
$scope.menu = $rootScope.menustructure;
});
MenuStructureService:
AppFactories.factory("MenuStructureService", function($rootScope, $http) {
return {
get: function() {
$http.get('/menustructure').success(function(data){
$rootScope.menustructure = data;
$rootScope.$broadcast('menustructure', 'updated');
return data;
});
}
}
});
后端根據當前的authstatus提供元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.