如何在Angular中创建服务

时间:2014-12-03 11:46:42

标签: angularjs dependency-injection

plunkr: http://embed.plnkr.co/qJWWRW/

我想让“dialogService”可用于我的应用中的所有/特定控制器。我停在了plunkr的最后一个运行版本。我认为我需要做的,但哪些不起作用是:

1)改变(app.js):

myAppServices.controller('dialogService' ...

myAppServices.service('dialogService'

2)向MainCtrl(app.js)添加依赖项:

myAppControllers.controller('MainController', ['$scope', '$http', '$routeParams', '$cookies', '$location', 'dialogService',
  function ($scope, $http, $routeParams, $cookies, $location, dialogService) {
    this.log = function(log) {

问题:
1)我哪里错了 2)在服务中使用customDialogCtrl,我是否也必须使它成为服务? 编辑: 根据这篇文章(https://www.airpair.com/angularjs/posts/top-10-mistakes-angularjs-developers-make),按类型构建它可能是一个坏主意。相反,我将按功能分组。它也拓宽了我的理解。因此,如果使用s.th.每个模型都需要依赖其他模型。来自其他模特。



我尝试按照本教程工作,但我将控制器放在一个单独的文件中。我加载所有控制器,依赖于控制器变量。 http://viralpatel.net/blogs/angularjs-service-factory-tutorial/(第5步)

2 个答案:

答案 0 :(得分:0)

我现在有解决方案。我想我对服务有误解。我删除了所有范围变量。定义了一个变量

thisService = this; 

改为使用它。在服务函数内部,我需要传递这个变量。

myDialog.service('dialogService',['$http','$timeout','dialogs',function($http,$timeout,dialogs){
    var thisService =this;
    thisService.message={};
    thisService.errors={};
    thisService.sucess=false;

    this.sendFeedback = function(name,email, thisService) {
      $http({
            url: 'php/log.php',
            method: "POST",
            // withCredentials: true,
            // headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
            data: {   what: 'feedback',
                      name: name,
                      email: email
                    }
          }).success(function(data, thisService) {

              if (!data.success) {
                // if not successful, bind errors to error variables
                thisService.errors= data.errors;
              } else {
                // if successful, bind success message to message
                thisService.message= data.message;
                thisService.sucess=true;
              }
            });
    };

    this.launch = function(which){
      switch(which){
        case 'error':
          dialogs.error();
          break;
        case 'notify':
          dialogs.notify();
          break;
        case 'confirm':
          var dlg = dialogs.confirm();
          dlg.result.then(function(btn){
            // this.confirmed = 'You confirmed "Yes."';
          },function(btn){
            // this.confirmed = 'You confirmed "No."';
          });
          break;
        case 'custom':
          var dlg = dialogs.create('/dialogs/custom.html','customDialogCtrl',{},{size:'lg',keyboard: true,backdrop: true,windowClass: 'my-class'});
          dlg.result.then(function(user){
            thisService.sendFeedback(user.name,user.email);
            dialogs.notify('Nachricht gesendet', 'Wir haben Deine Anfrage erhalten');
          },function(){
            //if nothing do xy

          });
          break;
      }
    }; // end launch



  }]);

  myDialog.controller('customDialogCtrl',function($scope,$modalInstance,data){
    //-- Variables --//

    $scope.user = {name : ''};
    $scope.user = {email : ''};


    //-- Methods --//

    $scope.cancel = function(){
      $modalInstance.dismiss('Canceled');
    }; // end cancel

    $scope.save = function(){
      $modalInstance.close($scope.user);
    }; // end save

    $scope.hitEnter = function(evt){
      if(angular.equals(evt.keyCode,13) && !(angular.equals($scope.user.name,null) || angular.equals($scope.user.name,'')) && !(angular.equals($scope.user.email,null) || angular.equals($scope.user.email,''))){
        console.log(!(angular.equals($scope.user.name,null) || angular.equals($scope.user.name,'')));
        console.log(!(angular.equals($scope.user.email,null) || angular.equals($scope.user.email,'')));
        $scope.save();}
      else
      {console.log(!(angular.equals($scope.user.name,null) || angular.equals($scope.user.name,'')));
        console.log(!(angular.equals($scope.user.email,null) || angular.equals($scope.user.email,'')));}
    };
  }); // end controller(customDialogCtrl)

  // .run(function($templateCache){
  //   $templateCache.put('/dialogs/custom.html','<div class="modal-header"><h4 class="modal-title"><span class="glyphicon glyphicon-star"></span> User\'s Name</h4></div><div class="modal-body"><ng-form name="nameDialog" novalidate role="form"><div class="form-group input-group-lg" ng-class="{true: \'has-error\'}[nameDialog.username.$dirty && nameDialog.username.$invalid]"><label class="control-label" for="course">Name:</label><input type="text" class="form-control" name="username" id="username" ng-model="user.name" ng-keyup="hitEnter($event)" required><span class="help-block">Enter your full name, first &amp; last.</span></div></ng-form></div><div class="modal-footer"><button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button><button type="button" class="btn btn-primary" ng-click="save()" ng-disabled="(nameDialog.$dirty && nameDialog.$invalid) || nameDialog.$pristine">Save</button></div>');
  // });

答案 1 :(得分:0)

我认为您首先需要了解的是服务,控制器和指令之间的区别以及如何以及何时使用它们。

控制器

使用控制器连接服务,依赖项和其他复杂逻辑,并将它们分配给视图范围。例如,在您希望将模型初始化为特定内容的视图中,一个非常简单的示例说明为什么或何时应该使用控制器:

angular.module('App',[]).controller('BasicCtrl', function(){
   this.myModel = { name: "foo" };
});

服务

您可以并且应该在以下情况下使用服务:a)您希望在应用程序的多个部分中应用或重用某些逻辑,并且b)想要在多个控制器之间传递一些数据。例如,我可以创建一个充当数据存储的服务,并在我的所有控制器上共享它:

angular.module("App",[]).service("DataService", function(){
     var data = [];

     return {
          add: function(item) {
              data.push(item);
          },
          getAllData: function() {
              return data;
          }
     }
}

在您注入此服务的每个控制器上,您都可以访问data数组,并可以重复使用它。

指令

当您想要与DOM交互时,应该使用指令,因此,这也是处理用户与页面的交互的好方法。例如,想象一下,我想在我的应用程序中添加一个记录用户反馈的按钮。我可以通过添加到我的页面来实现这一点:

<feedback-button feedback-type="custom"></feedback-button>

所有逻辑都应该在该指令中:

dialogModule.directive('feedbackButton', function(dialogs, $http){
  return {
    restrict: "E",
    replace: true,
    template: '<button class="btn btn-warning">Custom Dialog</button>',
    scope: {},
    link: function(scope, element, attributes) {
      scope.feedback = {};
      scope.user = {name : ''};
      scope.email = {email : ''};

      scope.sendFeedback = function() {
        $http({
          url: 'php/log.php',
          method: "POST",
          // withCredentials: true,
          // headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
          data: {   what: 'feedback',
                    name: scope.feedback.name,
                    email: scope.feedback.email
                  }
        }).success(function(data) {
          scope.message = null;
          scope.feedbackErrorName = null;
          scope.feedbackErrorEmail = null;
          // console.log(data);
          if (!data.success) {
            // if not successful, bind errors to error variables
              scope.feedbackErrorName = data.errors.name;
              scope.feedbackErrorEmail = data.errors.email;
          } else {
            // if successful, bind success message to message
              scope.message = data.message;
              scope.feedback.show=false;
          }
        });
      }

      scope.launch = function(which){
        switch(which){
          case 'error':
            dialogs.error();
            break;
          case 'notify':
            dialogs.notify();
            break;
          case 'confirm':
            var dlg = dialogs.confirm();
            dlg.result.then(function(btn){
              scope.confirmed = 'You confirmed "Yes."';
            },function(btn){
              scope.confirmed = 'You confirmed "No."';
            });
            break;
          case 'custom':
            var dlg = dialogs.create('custom.html','customDialogCtrl',{},{size:'lg',keyboard: true,backdrop: true,windowClass: 'my-class'});
            dlg.result.then(function(user){
              console.log(user);
              console.log(user.email);
              scope.feedback.name = user.name;
              scope.feedback.email = user.email;
              scope.sendFeedback();
            },function(){
              if(angular.equals(scope.feedback.name,''))
                scope.feedback.name = 'You did not enter in your name!';
                scope.feedback.email = 'You did not enter your email!';
            });
            break;
        }
      };

      element.on('click', function(){
        scope.launch(attributes['feedbackType']);
      });
    } 
  }

});

这是一个工作的plunker(我已经改变了一些与你相关的): http://plnkr.co/edit/7ECkZhW4BxFUMiclU23m?p=preview

编辑:只是想补充说这个代码可以被重构,并且sendFeedback方法可能应该被移动到服务中,因为功能类型(与后端服务器交互)更适合在服务中而不是在服务中。指令。