AngularJs 无法访问控制器中的表单对象($scope) [英] AngularJs can't access form object in controller ($scope)

查看:46
本文介绍了AngularJs 无法访问控制器中的表单对象($scope)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 bootstrap-ui 更具体地说是模态窗口.我有一个模态表单,我想要的是实例化表单验证对象.所以基本上我是这样做的:

<div class="form-group"><label for="answer_rows">答案行:</label><textarea name="answer_rows" ng-model="question.answer_rows"></textarea>

</表单><预>{{形式 |json}}</预

我可以毫无问题地在 html 文件中看到表单对象,但是如果我想从控制器访问表单验证对象.它只是向我输出空对象.这是控制器示例:

.controller('EditQuestionCtrl', function ($scope, $modalInstance) {$scope.question = {};$scope.form = {};$scope.update = 函数 () {控制台日志($scope.form);//空对象console.log($scope.question);//可以看到表单输入};});

我无法从控制器访问 $scope.form 的原因可能是什么?

解决方案

只针对那些不使用 $scope 而是使用 this 的人,在他们的控制器中,你'必须在表单名称之前添加控制器别名.例如:

<form name="clients.something"></表单>

然后在控制器上:

app.controller('ClientsController', function() {//设置 $setPristine()this.something.$setPristine();};

希望它也有助于整个答案集.

I am using bootstrap-ui more specifically modal windows. And I have a form in a modal, what I want is to instantiate form validation object. So basically I am doing this:

<form name="form">
    <div class="form-group">
        <label for="answer_rows">Answer rows:</label>
        <textarea name="answer_rows" ng-model="question.answer_rows"></textarea>
    </div>
</form>

<pre>
    {{form | json}}
</pre

I can see form object in the html file without no problem, however if I want to access the form validation object from controller. It just outputs me empty object. Here is controller example:

.controller('EditQuestionCtrl', function ($scope, $modalInstance) {
    $scope.question = {};
    $scope.form = {};

    $scope.update = function () {
        console.log($scope.form); //empty object
        console.log($scope.question); // can see form input
    };
});

What might be the reasons that I can't access $scope.form from controller ?

解决方案

Just for those who are not using $scope, but rather this, in their controller, you'll have to add the controller alias preceding the name of the form. For example:

<div ng-controller="ClientsController as clients">
  <form name="clients.something">
  </form>
</div>

and then on the controller:

app.controller('ClientsController', function() {
  // setting $setPristine()
  this.something.$setPristine();
};

Hope it also contributes to the overall set of answers.

这篇关于AngularJs 无法访问控制器中的表单对象($scope)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆