1. 程式人生 > >angular的uiRouter服務學習(1)

angular的uiRouter服務學習(1)

/*resolve*/
myapp.config(function($stateProvider){    
    $stateProvider.state('contacts',{
        url:'/contacts/:name',
        resolve:{
            //字串格式:使用一個既有的服務
            first:'aService',
            //函式:函式的返回值就是將被注入的服務
            second:function(){
                return {data:'second的data'}
            },
            
//函式:在函式中注入既有的服務 third:function(anotherService,$stateParams){ var data = anotherService.getName($stateParams.name); return {data:data} }, //函式:返回一個promise物件,最終得到的將是resolve裡的內容 fourth:function($q,$timeout){
var defer = $q.defer(); $timeout(function(){ defer.resolve({data:'我是fourth的data'}); //注意,如果一個state的resolve裡的某個promise被拒絕了,那這個state直接無法繼續下去了. //defer.reject({data:'我是fourth的data'}) },2000); return
defer.promise; }, //函式:返回$http返回的promise返回的promise,最終得到的是.then裡面return的內容 fifth:function($http){ return $http({ method:'GET', url:'/contacts/name' }).then(function(res){ return {data:res.data} },function(){ }) }, //函式:返回$http返回的promise,最終得到的就是後臺返回值. sixth:function($http){ return $http({ method:'GET', url:'/contacts/name' }) } }, templateUrl:function($stateParams){ return 'partials/contacts.' + $stateParams.name + '.html' }, controller:'ctrl' }) }); myapp.factory('aService',function(){ return { getName:function(){ alert('我是aService服務的getName方法') }, data:'first的data' } }); myapp.factory('anotherService',function(){ return { getName:function(data){ return data.toUpperCase() } } }); myapp.controller('ctrl',function($scope,first,second,third,fourth,fifth,sixth){ first.getName(); $scope.data1 = first.data; $scope.data2 = second.data; $scope.data3 = third.data; $scope.data4 = fourth.data; $scope.data5 = fifth.data; $scope.data6 = sixth.data; });