Ng-model不更新控制器的值 [英] Ng-model does not update controller value

查看:431
本文介绍了Ng-model不更新控制器的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Probably silly question, but I have my html form with simple input and button:

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

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

Then in the controller (template and controller are called from routeProvider):

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

为什么在控制台中看到正确更新但未定义的视图点击按钮?

Why do I see the view updated correctly but undefined in the console when clicking the button?

谢谢!

更新:
好​​像我已经解决了这个问题不得不提出一些解决方法):
只需将我的属性名称从 searchText 更改为 search.text ,然后在控制器中定义空 $ scope.search = {}; 对象,瞧...不知道为什么它的工作虽然;]

Update: Seems like I have actually solved that issue (before had to come up with some workarounds) with: Only had to change my property name from searchText to search.text, then define empty $scope.search = {}; object in the controller and voila... Have no idea why it's working though ;]

推荐答案

控制器为版本(推荐)

模板

<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

最好的是使用角度2的组件.x或角度1.5或以上

The best will be to use component with Angular 2.x or Angular 1.5 or upper

方式(不推荐)

不推荐这样做,因为一个字符串是一个原始的,强烈建议使用一个对象

This is NOT recommended because a string is a primitive, highly recommended to use an object instead

尝试这在你的标记中

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

这在您的控制器中

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

这篇关于Ng-model不更新控制器的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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