我需要访问父控制器 DynamicFormCtrl 中的表单数据(ng-model="name"
)。如何在 DynamicFormCtrl 中访问表单中的数据输入。我不知道如何访问它们。尽管可以在自己的范围内访问数据。
<body ng-app="exampleApp" ng-controller="DynamicFormCtrl as ctrl">
<div>
<button ng-click="ctrl.addForm(0)">Form One</button> //add form1
<button ng-click="ctrl.addForm(1)">Form Two</button> //add form 2
<button ng-click="ctrl.addForm(2)">Form Three</button>// add form 3
</div>
<div ng-repeat="form in ctrl.displayedForms track by $index"> //display form on button press
<ng-include src="form"></ng-include> //Include from from the Script
</div>
<script type="text/ng-template" id="form1.tpl.html">
<label>
{{name}}
Form one is an input: <input type="text" ng-model="name"/>
</label>
</script>
<script type="text/ng-template" id="form2.tpl.html">
<label>
Form two gives you choices: <input type="radio"/> <input type="radio"/>
</label>
</script>
<script type="text/ng-template" id="form3.tpl.html">
<button>Form three is a button</button>
</script>
<script type="text/javascript">
angular.module("exampleApp", [])
.controller("DynamicFormCtrl", function($scope) {
var ctrl = this;
$scope.form_name = $scope.name;
console.log($scope.form_name);
var forms = [
"form1.tpl.html",
"form2.tpl.html",
"form3.tpl.html",
];
ctrl.displayedForms = [];
ctrl.addForm = function(formIndex) {
ctrl.displayedForms.push(forms[formIndex]);
}
});
</script>
</body>
答案 0 :(得分:1)
当您使用controller-as语法时,您应该在输入字段中使用ctrl.name
<input type="text" ng-model="ctrl.name"/>
在控制器中,您可以使用ctrl.name
来使用输入当您使用controller-as语法时,您也不需要注入作用域。
进一步阅读控制器 - 正如我所推荐的那样 https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md