我有一个表单,其中包含一些已知的输入和一些包含在我无法控制但可以正确编写的部分中的内容。简化后如下所示:
<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", “年龄”}
。
最佳答案
事实证明,可以定义多个具有相同名称的指令,这样就变得很容易:
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/