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

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

问题描述

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

<button ng-click="check()">检查!</button>{{ 搜索文本 }}

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

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

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

谢谢!

更新:似乎我实际上已经解决了这个问题(之前不得不想出一些解决方法):只需将我的属性名称从 searchText 更改为 search.text,然后在控制器中定义空的 $scope.search = {}; 对象瞧...不知道为什么它会起作用;]

解决方案

Controller as 版本(推荐)

这里是模板

<input type="text" ng-model="$ctrl.searchText"/><button ng-click="$ctrl.check()">检查!</button>{{ $ctrl.searchText }}

JS

angular.module('example', []).controller('myController', function() {var vm = 这个;vm.check = 函数 () {控制台日志(vm.searchText);};});

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

最好使用 Angular 2.x 或 Angular 1.5 或更高版本的组件

#########

旧的方式(不推荐)

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

在你的标记中试试这个

<button ng-click="check(searchText)">检查!</button>{{ 搜索文本 }}

这在你的控制器中

$scope.check = function (searchText) {控制台日志(搜索文本);}

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 }}

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?

Thanks!

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 ;]

解决方案

Controller as version (recommended)

Here the template

<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>

The JS

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

An example: http://codepen.io/Damax/pen/rjawoO

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

########

Old way (NOT recommended)

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

Try this in your markup

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

and this in your controller

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

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

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