当重置表单中的数据时,希望设置form.setPristine()
,但是formController
还没有在$scope中注册。
这似乎是个愚蠢的问题,但我怎样才能找到 formController
?
在下面的代码中,得到“TypeError: Cannot call method 'setPristine' of undefined”
index.html
<ng-form name='wordForm' ng-controller='wordCntl' > ... </ng-form>
word.js
var langMod = angular.module('langMod', []); langMod.controller( 'wordCntl', function($scope,$http,$location) { // data $scope.dflt = { wrd_id: '', usr_id: '', ln: '', word: '' }; $scope.orig = {}; $scope.data = {}; // pull record default $scope.reset = function() { $scope.orig = angular.copy($scope.dflt); $scope.data = angular.copy($scope.orig); $scope.wordForm.setPristine(); } $scope.reset(); };
我知道访问 formController
的唯一方法是在 $scope
中设置它。但它还没有,我不知道如何找到它。
最佳答案
指令 Controller 在其他指令之间共享。要访问它,请在表单上创建一个自定义指令,它成为链接函数的第四个属性。
在您的自定义指令中,您可以这样做:
//inside custom directive
link: function(scope, element, attrs, controller){
controller.$setPristine();
}
我意识到这是对您问题的非常直白的回答。真正的解决方案可能是暂时不调用 $scope.reset ……你为什么需要调用?无论如何,您的表格不是从原始状态开始的吗?如果不是,是什么让它不是原始的?
关于javascript - 在 angularjs 中,我如何访问 formController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19921000/