可能是愚蠢的问题,但我有我的html表单简单的输入和按钮:

<input type="text" ng-model="searchText" />
<button ng-click="check()">Check!</button>
{{ searchText }}

然后在控制器中(模板和控制器由routeProvider调用):

$scope.check = function () {
    console.log($scope.searchText);
}

为什么我看到视图更新正确,但在控制台未定义时,单击按钮?

谢谢!

更新: 似乎我已经解决了这个问题(之前不得不提出一些变通办法): 只需要把我的属性名从searchText改为search。文本,然后定义空$scope。搜索= {};对象,瞧……但我不知道为什么它能起作用;]


当前回答

I came across the same issue when dealing with a non-trivial view (there are nested scopes). And finally discovered this is a known tricky thing when developing AngularJS application due to the nature of prototype-based inheritance of java-script. AngularJS nested scopes are created through this mechanism. And value created from ng-model is placed in children scope, not saying parent scope (maybe the one injected into controller) won't see the value, the value will also shadow any property with same name defined in parent scope if not use dot to enforce a prototype reference access. For more details, checkout the online video specific to illustrate this issue, http://egghead.io/video/angularjs-the-dot/ and comments following up it.

其他回答

看看这小提琴http://jsfiddle.net/ganarajpr/MSjqL/

我有(我想!)做了你一直在做的事情,看起来很有效。你能检查一下什么对你不起作用吗?

我只是在使用绑定到body元素的root_controller时遇到了这个问题。然后我在angular路由器中使用ng-view。问题是,当angular将html插入ng-view元素时,总是会创建一个新的作用域。因此,我的“check”函数是在ng-model元素修改的作用域的父作用域中定义的。

要解决这个问题,只需在路由加载的html内容中使用专用控制器。

我也有同样的问题。 正确的方法是将'searchText'设置为对象内部的属性。

但如果我想让它保持原样,一个字符串呢?我尝试了这里提到的每一种方法,都没用。 但随后我注意到问题只在初始化中,所以我刚刚设置了value属性,它工作了。

<input type="text" ng-model="searchText" value={{searchText}} />

这样,值就被设置为'$scope。searchText的值,当输入值改变时,它会被更新。

我知道这是个变通办法,但对我很管用。

I came across the same issue when dealing with a non-trivial view (there are nested scopes). And finally discovered this is a known tricky thing when developing AngularJS application due to the nature of prototype-based inheritance of java-script. AngularJS nested scopes are created through this mechanism. And value created from ng-model is placed in children scope, not saying parent scope (maybe the one injected into controller) won't see the value, the value will also shadow any property with same name defined in parent scope if not use dot to enforce a prototype reference access. For more details, checkout the online video specific to illustrate this issue, http://egghead.io/video/angularjs-the-dot/ and comments following up it.

为表单控件提供name属性