简单AngularJS形式是在不确定的范围 [英] Simple AngularJS Form is undefined in Scope

查看:146
本文介绍了简单AngularJS形式是在不确定的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始玩弄于的jsfiddle AngularJS形式,我已经遇到一个问题,已经在那里如预期一个非常简单的表单示例是行不通的。我只有一个指定的形式,它没有显示出来的范围出于某种原因(我期待用FormController实例)。

I'm starting to play around with AngularJS forms in jsfiddle and I've come across a problem already where a very simple form example is not working as expected. All I have is a named form and it's not showing up in scope for some reason (I'm expecting a FormController instance).

我有一个小提琴的成立,以下是基本的code:

I have a fiddle set up, and below is the basic code:

HTML

<div id="mainContainer" ng-app="angularTest" ng-controller="MainCtrl">
    <h1>The Form</h1>
    <form name="theForm">
        <input name="myName" type="text" ng-model="model.name" />
        <input name="submit" type="submit" />
    </form>
</div>

JS

var app = angular.module('angularTest', []);

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.model = { name: 'Model Name' };
    console.log($scope.theForm); //displays 'undefined'
}]);

我找不到了很多关于的jsfiddle这个简单的例子,所以我不知道这可能是与喜欢的网站一些奇怪的相互作用(我发现没有使用正规的控制器最例子)。我试着在Plunker检查为好,但我遇到同样的问题。

I can't find a lot of straightforward examples of this on jsfiddle, so I wasn't sure if this could be some strange interaction with sites like it (most examples I find aren't using formal controllers). I've tried on Plunker to check as well, but I encounter the same problem.

我敢肯定,我想的东西超明显,但我不能看到很多其他的事情来改变或调整在这里。任何帮助是极大AP preciated!

I'm sure I'm missing something super obvious, but I can't see many other things to change or tweak here. Any help is greatly appreciated!

推荐答案

该表格只有在控制器的 $范围将自己注册的之后的控制器已初步运行。因此,的console.log($ scope.theForm)将返回不确定的,即使一切都设置正确。

The form only registers itself with the $scope of the controller after the controller has initially run. Therefore the console.log($scope.theForm) will return undefined even if everything is setup correctly.

在你的榜样,以应对 theForm 的presence,可以设置在 theForm A守望者根据其presence设置调试文本:

In your example to react to the presence of theForm, you can setup a watcher on theForm to set debug text depending its presence:

$scope.$watch('theForm', function(theForm) {
    if(theForm) { 
        $scope.formDebugText = 'Form in Scope';
    }
    else {
        $scope.formDebugText = 'Form is Undefined';
    }        
});

可以在行动在 http://jsfiddle.net/9k2Jk/1/

这篇关于简单AngularJS形式是在不确定的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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