我正在尝试使用一些控件上的自定义操作来创建一个比一般复杂的表单。视图的主控制器保存将在最后保存的模型。在此主控制器中,我为每个具有某些特定操作的输入控件有一个单独的控制器。

这是一个简短的示例,问题是,如果要实现UserChoiceCtrl.selectLastUser函数,不使用$scope怎么办?

更一般而言,如何访问子控制器中主控制器中的模型?在视图中很容易,但是如何在控制器代码中完成呢?

@Plunker if you prefer



angular.module('myApp', []);

angular.module('myApp')
  .controller('TaskCtrl', [
    function() {
      var viewModel = this;

      // This is injected in controller in real life
      viewModel.users = [
        {login: 'Tom', password: '123'},
        {login: 'Stanley', password: '123'},
        {login: 'Joe', password: '123'},
        {login: 'Katy', password: '123'},
        {login: 'Kate', password: '123'},
        {login: 'Tony', password: '123'}
      ];

      viewModel.task = {
        user: viewModel.users[0],
        description: ''
      };

      viewModel.save = function() {
        alert(angular.toJson(viewModel.task));
      };
    }
  ]);

angular.module('myApp')
  .controller('UserChoiceCtrl', [
    function() {
      var viewModel = this;

      viewModel.selectLastUser = function() {
        // No way to access the task variable @ TaskCtrl ?

        // The following line is working but using $scope
        // $scope.taskCtrl.task.user = $scope.taskCtrl.users[5];
      };
    }
  ]);

body {
  font-family: 'Arial';
}
label,
input,
textarea {
  display: block;
}
label {
  margin-top: 8px;
}

<!DOCTYPE html>
<html data-ng-app="myApp">

<head>
  <script data-require="[email protected]" data-semver="1.4.0" src="https://code.angularjs.org/1.4.0/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body data-ng-controller="TaskCtrl as taskCtrl">
  <h1>New task</h1>
  <form name="taskCtrl.taskForm">
    <label>Description</label>
    <textarea data-ng-model="taskCtrl.task.description"></textarea>
    <div data-ng-controller="UserChoiceCtrl as userChoiceCtrl">
      <label>User</label>
      <select data-ng-model="taskCtrl.task.user" data-ng-options="user as user.login for user in taskCtrl.users"></select>
      <button data-ng-click="userChoiceCtrl.selectLastUser()">Last user of list</button>
    </div>
    <br>
    <button data-ng-click="taskCtrl.save()">Save</button>
  </form>
</body>

</html>

最佳答案

尝试这个

<button data-ng-click="userChoiceCtrl.selectLastUser(taskCtrl.task.user)">Last user of list</button>

 viewModel.selectLastUser = function(user) {
        alert(user);
        // No way to access the task variable @ TaskCtrl ?

        // The following line is working but using $scope
        // $scope.taskCtrl.task.user = $scope.taskCtrl.users[5];
   };

08-16 23:31