我有一个表单,其中包含一些已知的输入和一些包含在我无法控制但可以正确编写的部分中的输入。简化后看起来像这样:
<form ...>
<input name="input1" type="hidden" value="1">
<div class="from_partial" ng-controller="Controller">
<!-- here goes first partial -->
<button type="button" ng-click="check()">Check</button>
</div>
<div class="from_partial" ng-controller="Controller">
<!-- here goes second partial -->
<button type="button" ng-click="check()">Check</button>
</div>
</form>
部分看起来像这样:
<div class="item">
<input type="text" ng-model="name"/>
</div>
<div class="item">
<input type="text" ng-model="age"/>
</div>
现在我需要以某种方式在 Controller 的
check()
中使用这些输入。功能,分别为每个部分。我事先不知道他们的名字。枚举它们的最佳方法是什么?当 Angular 使用他们的 $scope
引导和连接特定模型时,是否可以获得它们(即找出他们的名字)? ?换句话说,我希望每个
Controller
知道输入名称的对象,例如 $scope.input_names
包含 {"name", "age"}
.
最佳答案
事实证明,可以定义多个具有相同名称的指令,这样就变得容易了:
angular.module(app_name)
.controller("Controller", ['$scope', function ($scope) {
$scope.input_names = [];
...
}])
.directive('ngModel', function() {
var linker = function(scope, element, attrs) {
scope.input_names.push(attrs.ngModel);
}
return {
restrict: 'A',
priority: 100,
require: '?ngModel',
link: linker
};
});
原始的 Angular 指令被定义为优先级 1,并将首先执行。然后自定义指令将插入使用
ng-model
定义的名称scope.input_names
的属性.这确保每个 Controller 将只获得相关部分中定义的名称。与 ng-model
相关的所有其他内容将照常工作。
关于javascript - Angular - 在 Bootstrap 上提取指令的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45631843/