AngularJs - 在控制器

时间:2017-08-08 15:00:21

标签: javascript 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>

   

2 个答案:

答案 0 :(得分: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>

   

答案 1 :(得分:1)

appServicesProvider&#39; postFunction的问题未被调用,因为您未在[{1}}上公开appServicesProvider服务。简而言之,$scope中暴露的任何内容都可以在html上访问。

$scope

上面只会解决您的问题,这不是一个好方法,因为您不必要地从HTML服务中公开了所有内容。而是通过创建自己的方法angular.module("myApp") .controller("AdminController",function($scope, $http, appServicesProvider) { $scope.appServicesProvider = appServicesProvider )}; ,仅在$scope上公开所需的服务方法。

postFunction

<强> HTML

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