我应该在指令和服务之间传递数据吗?

Should I pass data between directive and service?

我有一个带有 控制器 的页面,它有一个 指令 显示带有输入的表单。

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

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

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

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

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

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

directive's template 应该与 directive's scope 对话并显示表格。

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

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

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
  }

session/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>
 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 
    }
});