2014-11-04 139 views
0

我一直在使用AngularJS瓦特/ UI路由器在過去幾個月,我一直在遇到相同的用例,我似乎無法找到一個優雅的解決方案......我有一個循序漸進的網絡規劃應用程序用戶必須通過完成訂單。

我有一個根控制器住在ui路由器作用域之外(根控制器沒有'狀態'),我一直試圖在我的web規劃器中保存每個頁面全局的一些數據。這些信息就像客戶信息和訂單名稱一樣,將在整個過程中顯示在計劃者的頂部和底部。

我的問題是,爲了將這些數據導入到一個Angular服務中,以便它可以在我的控制器之間共享,我需要我們正在討論的命令的OrderId。這個OrderId存在於URL $ stateParams中,但問題是我的'root'控制器在ui-router被涉及之前被實例化,這意味着我無法從這個控制器內部訪問我的$ stateParams。

我已經使用了Angular的$broadcast信號告訴我的根控制器何時終於在url中找到了OrderId,但是這個解決方案並不覺得「正確」。有誰知道有什麼更好的方法來處理「全局」信息,而無需在我的應用程序的每個控制器中向我的服務添加查詢?

// This is the root of my web app 
<div ng-app="MyApp.backups.new" ng-controller="NewController"> 

    // This is where I need to display some "global" information 
    <h2 class="dashTitle"><sk-img class="iBackup-Add"></sk-img> New Backup {{ (Master.Service.Name ? '- ' + Master.Service.Name : '') }}</h2> 
    <div id="wpMenuContainer" class="wpMenuContainer"> 
     <ul class="wpMenu clearfix"> 
      <li ng-repeat="chevron in Chevrons | filter:{disabled:false}" ng-class="{ active : chevron.active, navable : $index < Index }" class="backupChevron" ng-click="!($index < Index)||navigate(chevron, $index)"> 
       <img ng-if="!$last" src="/App_Themes/App/images/misc/clear.gif" class="iMenuArrow"> 
       <span>{{ chevron.name }}</span> 
      </li> 

      </ul> 
    </div> 
    // The problem is ui-router's scope lives within this <div ui-view></div>, so I can't access $stateParams until these child controllers are created 
    <div ui-view></div> 

</div> 

回答

0

您是否試過利用UI路由器的state change events

// custom factory for setting/getting current state params 
app.factory('customFactory', function(){ 
    var currentParams = null; 

    return { 
    getParams: function(){ return currentParams; }, 
    setParams: function(params){ currentParams = params; } 
    }; 

}); 

// your controller 
app.controller('NewController', ['customFactory', function(customFactory){ 
    var routeParams = function(){ 
    return customFactory.getParams() || {}; 
    }; 

    $scope.orderID = routeParams().OrderId; 
}]); 

// set listener on the '$stateChangeSuccess' event to update the params in your factory 
app.run(['$rootScope', 'customFactory', function($rootScope, customFactory){ 

    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ 
    customFactory.setParams(toParams); 
    }); 

}]); 

這樣,您只需要在'app.run'和那個1控制器中引用'customFactory'服務。我還沒有在小提琴或任何東西中測試過這些,但這個想法應該能讓你走上正軌。

+0

是的,所以我目前正在使用$ stateChangeSuccess事件來設置'$ rootScope.OrderId'到正確的orderId,當它在toParams中被找到時......問題在於當這個父控制器不知道這個時候param通過使用'routeParams'函數設置 – 2014-11-05 02:36:44

+0

@MattHintzke,該函數不斷從工廠返回更新後的值,控制器值'$ scope.orderID' *應該在每次發生'$ stateChangeSuccess'時更新。但是如果你希望在你的父控制器中發生一個'$ scope.orderID'更新時發生的事情,可以試試'$ scope。$ watch('orderID',function(newVal,oldVal){/ * your callback * /}) ;' – SteamDev 2014-11-06 21:06:27