Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

angularjs - ng-model is undefined in controller

I'm using ionic and I have the following view:

<ion-view hide-nav-bar="true" ng-controller="loginController" class="login-view">
  <ion-content class="padding">

    <div class="row row-center">
      <div class="col">

        <div id="logo"></div>

        <form>
          <div class="list">
            <label class="item item-input">
              <input type="text" placeholder="Membership No" ng-model="membershipNo">
            </label>
            <label class="item item-input">
              <input type="password" placeholder="Password" ng-model="password">
            </label>
          </div>

          <button class="button button-block button-positive button-login" ng-click="login()">
            Login
          </button>
        </form>

      </div>
    </div>

  </ion-content>
</ion-view>

And my controller:

app.controller('loginController', ['$scope', '$localstorage',
    function($scope, $localstorage) {

        $scope.membershipNo;
        $scope.password;

        $scope.login = function () {
            console.log("User logged in with membership no: " + $scope.membershipNo +
    "
 and password: " + $scope.password);
        }

    }
]);

What I don't understand, is that when I click the button, the login function is called correctly. Also, if in the controller I go and set $scope.membershipNo to something like "Banana Pancake", the view actually updates.

Yet when the login function actually runs, is says that membershipNo and password are undefined. I'm fairly new to Angular and Ionic so I know this is probably some n00b mistake...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had exact the same issue recently and that's probably a solution: https://stackoverflow.com/a/22768720/552936

Modified quote:

"If you use ng-model, you have to have a dot in there."
Make your model point to an object.property and you'll be good to go.

Controller

$scope.formData = {};
$scope.login = function () {
  console.log("User logged in with membership no: " + $scope.formData.membershipNo +
  "
 and password: " + $scope.formData.password);
 }

Template

<input type="text" placeholder="Membership No" ng-model="formData.membershipNo">
<input type="password" placeholder="Password" ng-model="formData.password">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...