2017-08-08 64 views
2

我是AngularJs的新手,在嘗試避免在不同的控制器中編寫相同的代碼時遇到了問題。AngularJs - 在控制器中使用工廠函數

我已經創建了一個應該保存所有功能的工廠,而控制器能夠使用這些功能,並將一個功能從控制器移到該工廠。 我創建了一個函數,它應該從一個表單發佈數據,但是當我點擊它來執行時,從字面上看沒有任何反應。

我在google和stackoverflow上搜索了一段時間,找不到適合我的問題的任何問題。

有什麼我錯過了或做錯了嗎?

廠:

(function(){ 
    angular.module("myApp").factory('appServicesProvider',function($http) { 

    var restURL = "http://localhost:8080/Project/rest/api/"; 

    function postFunction(data){ 

     $http.post(restURL, JSON.stringify(data)).then(
       function(response){ 
       }   
     ); 
    } 

    return{postFunction:postFunction} 

}); 
})(); 

控制器:

(function() { 

angular.module("myApp") 
.controller("AdminController",function($scope, $http, appServicesProvider) { 

$scope.restURL = "http://localhost:8080/Project/rest/api/"; 

)}; // There's more code but it's irrelevant to the function I'm talking 
     about 

HTML:

<div id="postFunctionDiv" class="form-group row"> 
    <div class="col-xs-4"> 
    <label>PostFunction</label> 

<!--- 
Some form inputs 
---!> 

<button class="btn btn-success" ng- 
click="appServicesProvider.postFunction(data)" >Execute</button> 
</div> 

回答

3

ng-click應該調用一個函數的範圍在控制器內,而不是試圖直接調用工廠內的方法。那個控制器的功能就是調用工廠方法。例如:

控制器:

(function() { 

angular.module("myApp") 
.controller("AdminController",function($scope, $http, appServicesProvider) { 

$scope.restURL = "http://localhost:8080/Project/rest/api/"; 

$scope.postFn = function(data) { 
    appServicesProvider.postFunction(data); 
}; 

)}; // There's more code but it's irrelevant to the function I'm talking 
     about 

HTML:

<div id="postFunctionDiv" class="form-group row"> 
    <div class="col-xs-4"> 
    <label>PostFunction</label> 

<!--- 
Some form inputs 
---!> 

<button class="btn btn-success" ng- 
click="postFn(data)" >Execute</button> 
</div> 

+0

啊!我看到你在那裏做了什麼:) 非常感謝你! –

1

的問題appServicesProviderpostFunction沒有打電話,因爲您沒有在$scope上暴露appServicesProvider服務。總之在$scope中暴露的任何內容都可以通過html訪問。

angular.module("myApp") 
.controller("AdminController",function($scope, $http, appServicesProvider) { 

    $scope.appServicesProvider = appServicesProvider 

)}; 

上面會只是解決您的問題,那會不會是去爲你的HTML暴露一切從服務不必要的好辦法。而只是通過創建您自己的方法postFunction而僅在$scope上暴露出期望的服務方法。

angular.module("myApp") 
.controller("AdminController", 
function($scope, $http, appServicesProvider) { 
    $scope.postFunction = function (data) { 
     appServicesProvider.postFunction(data) 
    } 
} 
); 

HTML

ng-click="postFunction(data)" 
+0

我很抱歉,但你建議沒有奏效。 –

+0

@DorGolan我的壞。我的代碼中存在拼寫錯誤。我糾正了。你可以試試嗎? –

+0

現在它與上面提到的Kyle建議的代碼相同,它可以工作:) 謝謝! –