可能是愚蠢的问题,但我有我的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。搜索= {};对象,瞧……但我不知道为什么它能起作用;]


当前回答

我也面临着同样的问题…… 对我来说有效的解决方法是使用这个关键字..........

警报(this.ModelName);

其他回答

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.

“如果你使用ng-model,你必须在那里有一个点。” 让你的模型指向一个对象。你就可以走了。

控制器

$scope.formData = {};
$scope.check = function () {
  console.log($scope.formData.searchText.$modelValue); //works
}

模板

<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>

这种情况发生在子作用域在类似游戏的子路由或ng-repeat中。 子作用域创建自己的值,并产生名称冲突,如下所示: 详见视频片段:https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s

对我来说,这个问题是通过将我的数据存储到一个对象(这里是“数据”)来解决的。

NgApp。controller('MyController',函数($scope) { 美元的范围。My_title = "";//这在ng-click函数中不起作用 美元的范围。数据= { 'my_title': "", }; 美元的范围。doAction = function() { console.log ($ scope.my_title);//错误值 console.log ($ scope.datas.my_title);// Good Value由'ng-model'绑定 } });

我希望它会有帮助

控制器为版本(推荐)

这里是模板

<div ng-app="example" ng-controller="myController as $ctrl">
    <input type="text" ng-model="$ctrl.searchText" />
    <button ng-click="$ctrl.check()">Check!</button>
    {{ $ctrl.searchText }}
</div>

JS的

angular.module('example', [])
  .controller('myController', function() {
    var vm = this;
    vm.check = function () {
      console.log(vm.searchText);
    };
  });

示例:http://codepen.io/Damax/pen/rjawoO

最好是在Angular 2中使用component。x或Angular 1.5或更高版本

########

旧方式(不推荐)

不建议这样做,因为字符串是原语,强烈建议使用对象

在标记中试试这个

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

这是你的控制器

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

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

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