【问题标题】:Should I pass data between directive and service?我应该在指令和服务之间传递数据吗?
【发布时间】:2015-06-28 08:45:42
【问题描述】:

我有一个带有 controller 的页面,该页面有一个 directive,用于显示带有输入的表单。

指令 有一个对象,其中包含显示在表单上的所有输入(及其 ng 模型)。这会将表单输入数据绑定到指令内的对象变量。

我需要显示提交表单数据的结果(和其他操作)。

为此,我创建了一个处理业务逻辑和 ajax 调用的服务

这里的问题是...... 我应该如何从服务访问表单数据以执行所需的操作?我考虑过从服务访问指令变量,但我不确定怎么做,如果这首先是正确的方法。

【问题讨论】:

    标签: javascript angularjs model-view-controller angularjs-directive angular-services


    【解决方案1】:

    service 应该包含一个模型,该模型基本上是表单的 javascript 对象。

    directive 应该注入服务并将该对象添加到他的作用域中(引用)。

    directive's template 应与directive's scope 通话并显示表单。

    更改视图上的值将反映服务,因为它们具有相同的引用,并且视图将更新指令范围,因为有两种方式绑定。

    【讨论】:

    • 然后,据我了解,我必须将对象模型移动到服务中,然后指令将使用服务中的变量。这种注入有什么最佳实践吗?
    • 服务应保持状态并执行所有 $http 调用。控制器和指令应该注入服务并访问状态。控制器应该执行数据绑定并充当 html 最好的朋友。
    【解决方案2】:

    诚然,我仍在努力解决问题,但我认为如果您在指令和服务之间添加一个控制器,事情会更加清晰。这是我一直在玩的基本结构中最紧凑的示例。(如果这不是你的东西,请原谅咖啡脚本)。

    angular.module 'app'
    
    .controller 'KeyFormCtrl', (SessionService, $scope, $location, $log) ->
      @error = null
      @message = null
      @keySent = false
      @creds =
        username: null
    
      @sendKey = ->
        SessionService.sendKey({ username: @creds.username })
        .then(
          (resp) =>
            @keySent = true
          (err) =>
            @error   = err.error
        )
    
    .directive 'eaKeyForm', ->
      {
        restrict: 'AE'
        scope: {}
        templateUrl: 'session/key-form.html'
        replace: true
        controller: 'KeyFormCtrl'
        controllerAs: 'kfc'
        bindToController: true
      }
    

    会话/key-form.html:

    <form>
        <div ng-show="kfc.error">{{kfc.error}}</div>
        <div ng-show="kfc.message">{{kfc.message}}</div>
        <div ng-show="kfc.keySent">
            An account key has been sent to {{kfc.creds.username}}.<br />
        </div>
        <div ng-hide="kfc.keySent">
            <input type="email" ng-model="kfc.creds.username">
            <button ng-click="kfc.sendKey()">Send Key</button>
        </div>
    </form>
    

    【讨论】:

      【解决方案3】:
       angular.module('myApp', [])
           .directive('myAweseomDirective', ['MyAwesomeService', function(MyAwesomeService) {
               return {
                   link: function(scope) {
      
                       scope.saveFormDetails = function() {
                           MyAweseomeService.saveInformation(scope.data);
                           //where data is the ng-model for the form
                       }
                   }
               };
      }])
      .service('MyAweseomService', function() {
          MyAwesomeService.saveInformation = function(data) {
              //do whatever you want to with the data 
          }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-03
        • 2014-03-19
        • 2016-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        相关资源
        最近更新 更多