2015-05-01 77 views
1

控制器代碼從AngularJS一個控制器調用服務功能

'use strict'; 

angular.module('MyApp').controller('ArticleContribEmailController', [ 

    '$scope', 'ArticleAppState', 'fbsUserDataService', 'contribEmailService', 
    function ($scope, ArticleAppState, fbsUserDataService, contribEmailService) { 

     this.userChanged = function() { 

      if (fbsUserDataService.initialized && fbsUserDataService.user && ArticleAppState.page_data) { 

       // user has authenticated. 
       contribEmailService.initForm(); 

      } 

     }; 


     // watch for when user data is available, run userChanged. 
     $scope.$watch(function() { return fbsUserDataService.user; }, this.userChanged); 
     $scope.$watch(function() { return fbsUserDataService.initialized; }, this.userChanged); 
    } 
]); 

服務代碼

'use strict'; 

angular.module('forbesArticleApp').service('contribEmailService', [ 

    '$injector', '$route', 'ArticleAppState', 'fbsUserFormFactory', 'fbsUserDataService', 

    function initForm ($injector, $route, ArticleAppState, fbsUserFormFactory, fbsUserDataService) { 

     console.log("Hello world!"); 

    } 

]); 

我只是想火在我的控制器調用的contribEmailService.initForm()功能,但它在頁面加載後立即觸發。

如何設置何時調用服務功能initForm()

回答

1

以下是更正服務代碼:

'use strict'; 

angular.module('forbesArticleApp').service('contribEmailService', [ 
    '$injector', '$route', 'ArticleAppState', 'fbsUserFormFactory', 'fbsUserDataService', 

function($injector, $route, ArticleAppState, fbsUserFormFactory, fbsUserDataService) { 
    return { 
     initForm: function() { 
     console.log("Hello world!"); 
     } 
    }; 
]); 

的服務功能是一個工廠,將依次返回實際的服務。所以它會在第一次被請求作爲依賴時運行。實際上,contribEmailService在你的函數中應該是undefined,因爲你的工廠實際上並沒有返回任何東西。

希望這會有所幫助!

0
controller:- 
blogcontroller is controller name 

app.controller('blogController', function($scope, $compile, $http, blogAuth, AppInfo, $location,$element){ 

$scope.blog_abuse = function(blog_id) 
    { 

     blogAuth.BlogAbuse(blog_id).then(function(response) 
     { 
      $scope.DetailblogList.is_abused = response.records.is_abused; 
     },function(error){ 
     }); 
    } 
}); 


service:- 

app.factory('AppInfo', function(){ 
    return { 
     serviceURL:site_url 
    }; 
}); 

app.service('blogAuth', function($http, $rootScope, $q, AppInfo){ 

this.BlogAbuse = function(blog_id){ 
    var deferred = $q.defer(); 
    var pageObj ={"blog_id":blog_id}; 

     $http.post(AppInfo.serviceURL+'blog/blog_abuse',pageObj).success(function(data){ 
      deferred.resolve(data); 
     }).error(function(msg, code) {   
      console.log('error', code, msg); 
     }); 
     return deferred.promise; 
    } 

}); 
相關問題