zoukankan      html  css  js  c++  java
  • Ng-model undefined in the controller

    这个问题是我最近在项目中碰到的,暂时没找到原因,找到一个解决方法,还多请大神指教,在Stack Overflow找到解决方法:

    I am having some "problems" reading an ng-model from the controller.

    I want to do this:

    <input type="text" ng-model="code">
    <button ng-click="setCode()">Login</button>

    And in my controller access that variable like this:

    $scope.setCode = function(){
        alert($scope.code);
      }

    That is what I want to do but my code variable is undefined.

    I found 2 ways to get this to work:

    1) Passing the variable as an argument

    <input type="text" ng-model="code">
    <button ng-click="setCode(code)">Login</button>

    and:

    $scope.setCode = function(code){
        alert(code);
      }

    2) Declaring my variable as an object

    <input type="text" ng-model="code.text">
    <button ng-click="setCode()">Login</button>

    and:

    复制代码
    $scope.code = {text: 'foo'};
    
    [...]
    
    $scope.setCode = function(){
        console.log($scope.code);
      }
    复制代码

    (I prefer the second one)

    But I am a little confused about what I should do. It's ok to declare my ng-models like objects? I have to declare ALL my models like objects?

    EDIT: Here is a Plnkr of the problem

    In this example (I am using the Ionic framework), I declare a variable code with the value test, when I change the model in the input and press the Start button, in theory I have to see in an alert the new value of the model. But what I see is the old one.

    Thanks!

    解决:

    I fixed your plnkr example using object model instead of primitive type.

    $scope.model = {};
    $scope.model.code = "test";
    
    $scope.setCode = function(){
        alert($scope.model.code);
    }

     转:http://stackoverflow.com/questions/22762725/ng-model-undefined-in-the-controller

  • 相关阅读:
    6.5 列出当前目录所有文件
    6.4 协程写文件
    6.3 写文件
    6.2 创建空目录
    6.1 os 获取文件状态
    5.13 json
    es2016
    短路原理
    fexbox
    vue @
  • 原文地址:https://www.cnblogs.com/susanws/p/5474981.html
Copyright © 2011-2022 走看看