控制器读取组件数据

Controller reading component data

我的想法是用分离的组件创建一个大表单。所以这是我的主要模板:

<form novalidate>
    <div class="row">
        <user></user>
    </div>
    <button type="button" class="btn btn-default" ng-click="submit()"> Submit   </button>
</form>

及其控制器(模板从ui路由配置绑定到控制器)

(function () {
    'use strict';

    angular.module('app')
        .controller('formCtrl', formCtrl);

    function formCtrl ($scope) {
        $scope.submit = function() {
            console.log("read data");
        }
    }      
})();

现在,用户组件:

(function () {
    'use strict';

    var module = angular.module('app.user');

    module.component("user", {
        templateUrl: "app/user/user.html",
        controllerAs: "model",
        controller: function () {
            var model = this;
            model.user = {};            
        }
    });
})();

和用户模板:

<form novalidate>
    <form-group>
        <label for="inputUser"> Name <label>
        <input ng-model="model.user.name" id="inputUser" type="text" placeholder="User"/>
    </form-group>
    <form-group>
        <label for="inputUser"> Email <label>
        <input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email"/>
    </form-group>
    <div>
        {{model.user | json}}
    </div>
</form>

现在我希望能够在用户提交时读取用户数据。我该怎么做?

一个可能的解决方案是 $$childTail。所以如果我想访问用户:

$scope.$$childTail.model.user

使用组件时,根据组件的类型(智能或非智能),您必须向父控制器发出输出以处理此类事情。但在这种情况下,您可以使用 ngModel 来处理模型并从组件内在父级上更改它。例如:

工作片段:

angular.module('app', [])
  .controller('formCtrl', function($scope) {
    $scope.user = {};
    $scope.submit = function() {
      console.log($scope.user);
    }
  })
  .component("user", {
    bindings: {
      user: '=ngModel'
    },
    templateUrl: "app/user/user.html",
    controllerAs: "model",
    controller: function() {}
  });

angular.element(function() {
  angular.bootstrap(document, ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<form novalidate ng-controller="formCtrl">
  <div class="row">
    <user ng-model="user"></user>
  </div>
  <button type="button" class="btn btn-default" ng-click="submit()">Submit</button>
</form>

<script type="text/ng-template" id="app/user/user.html">
  <form novalidate>
    <div>
      <label for="inputUser">Name
        <label>
          <input ng-model="model.user.name" id="inputUser" type="text" placeholder="User" />
    </div>
    <div>
      <label for="inputUser">Email
        <label>
          <input ng-model="model.user.email" id="inputUser" type="email" placeholder="Email" />
    </div>
    <div>
      {{ model.user | json }}
    </div>
  </form>
</script>