gpt4 book ai didi

angularjs - 如何在 $scope 中按名称获取表单?

转载 作者:行者123 更新时间:2023-12-02 06:00:42 25 4
gpt4 key购买 nike

如何在$scope中通过名称获取表单?

测试示例:

<div ng-controller="solod">
<form name="good_f">
<input type="text" name="super">
</form>
</div>

<script>
function solod($scope){
console.log($scope.good_f) //undefined
}
</script>

这可能吗?谢谢

最佳答案

您通常不希望 Controller 像这样访问表单,这会将 Controller 与 View 结构耦合得太紧。相反,像这样将表单传递给 Controller ​​......

<div ng-controller="solod">
<form name="good_f" ng-submit="submit(good_f)">
<input type="text" name="super">
</form>
</div>



<script>
function solod($scope){
$scope.submit = function(theForm){
console.log(theForm)// not undefined
console.log($scope.good_f) // will exist now also
};

// do stuff in a watch
$scope.$watch("good_f", function(formVal){ console.log(formVal);});
}
</script>

否则,如果你只是想跟踪文本输入的值,给它一个ng-model

编辑:在进一步的研究中,$scope 将 good_f 作为一个属性,只是当您在构造函数中记录它时不会。如果你愿意,你可以在 good_f 上设置一个 watch ,但我仍然认为你应该把它传进去。

name (optional) string Name of the form. If specified, the form controller will be published into related scope, under this name.

https://docs.angularjs.org/api/ng/directive/form

关于angularjs - 如何在 $scope 中按名称获取表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25861051/

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