gpt4 book ai didi

javascript - 具有嵌套 Controller 和 "controller as"语法的表单

转载 作者:行者123 更新时间:2023-11-30 16:48:45 25 4
gpt4 key购买 nike

我正在尝试通过对某些控件的自定义操作来创建一个超出平均水平的复杂表单。 View 的主 Controller 持有将在最后保存的模型。在这个主 Controller 中,我为每个具有一些特定操作的输入控件设置了一个单独的 Controller 。

这是一个简短的例子,问题是,如果我想实现 UserChoiceCtrl.selectLastUser 功能,我怎么能不使用 $scope 呢?

更一般地说,我如何在子 Controller 中访问主 Controller 中的模型?这在 View 中很容易,但我该如何在 Controller 代码中执行?

@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="angular.js@1.4.0" 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];
};

关于javascript - 具有嵌套 Controller 和 "controller as"语法的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30850053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com