加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 当表单在指令中时,如何访问FormController?

发布时间:2020-12-17 17:21:31 所属栏目:安全 来源:网络整理
导读:以下是我的指示: restrict: 'E',scope: {},templateUrl: 'directives/my.directive.html',link: function(scope) { // Want to be able to access "myForm" here (eg: to setPristine(),etc) scope.bla = {}} 以下是模板中: form name="myForm" novalidate
以下是我的指示:

restrict: 'E',scope: {

},templateUrl: 'directives/my.directive.html',link: function(scope) { 
    // Want to be able to access "myForm" here (eg: to setPristine(),etc)
    scope.bla = {}
}

以下是模板中:

<form name="myForm" novalidate>
    <input name="inputOne" type="text" ng-model="bla.name" required/>
</form>

我试过了:

console.log(scope.myForm) // shows undefined

和:

<form name="myForm" novalidate>
    <div ng-init="bla.newForm = myForm"></div>

    <input name="inputOne" type="text" ng-model="bla.name" required/>
</form>

console.log(scope.bla.newForm) // Undefined

请不要告诉我:

require: '^form'

我收到错误:无法获取FormController.这是正确的,因为表单是指令的一部分而不是父模板/范围

真的很感激这里的一些帮助.

解决方法

从表单获取表单控制器的一种非常简单的方法,无论范围如何(或者如果您需要从另一个控制器,服务或指令访问它),都是使用angular.element.

angular.element("[name='myForm']").controller("form");

需要注意的是,表单必须已经加载/编译到DOM中,但是由于您在链接函数中执行此操作,因此它应该已经呈现.如果未定义,请尝试将其包装在$timeout中以使摘要有机会运行.

$timeout(function() { angular.element("[name='myForm']").controller("form"); });

这不是非常“最佳实践”,但如果您已经用尽了其他选择,那就太棒了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读