0

I'm trying to make a very simple signup form, which is supposed to work in 2 steps.

  • I ask the user for his email in the first step
  • in the second step, I ask the user for the other details (step == 2).

The template is simple;

<div class="input-group layout-container" ng-switch on="step">
    <!-- Login -->
    <img src="images/yeoman.png">
    <p>{{msg}}</p>
    <form name="signup">
        <input type="text" class="form-control login" placeholder="firstname" ng-model="firstname" ng-switch-when="2">
        <input type="text" class="form-control login" placeholder="lastname"ng-model="lastname" ng-switch-when="2">
        <input type="email" class="form-control login" placeholder="email" ng-model="email" ng-switch-when="1" required>
        <span class="error" ng-show="signup.input.$error.required">Cannot be blank</span>
        <span class="error" ng-show="signup.input.$error.email">Not a valid email</span>
        <input type="password" class="form-control login" placeholder="password" ng-model="pass" ng-switch-when="2"> <br/><br/>
        <div class="btn-container">
            <button class="btn btn-primary" ng-click="next()">Next</button>
        </div>
    </form>
</div>

As you can see, there's some basic validation going on as well, and I assign the value of the email to a model I call email.

And the controller goes like this:

.controller('SignupCtrl', function ($scope) {
    $scope.msg = "First, your email";
    $scope.step = 1;
    $scope.email = ''; // this still doesn't help
    $scope.$watch('email', function (now, then, scope) {
        console.log('email change', now, then);
    });
    $scope.next = function () {
        $scope.step = Math.min($scope.step + 1, 2);
    };
})

The problem is this: the $watch on 'email' doesn't ever trigger at all. Where's this going wrong?

4

2 回答 2

2

我同意@miqid,它ng-switch隐式地创建了一个新范围。的所有值变化<input>实际上都发生在这个孤立的子范围内。它的父母,你在哪里$watch,不会被通知。这就是您无法观察变量变化的原因。这是 Angular 用户的常见陷阱。

LT;DR只需将任何更改ng-model="foo"ng-model="$parent.foo"您的ng-switch块中。

于 2015-09-24T03:56:12.763 回答
1

这是一个有效的 jsfiddle(只是您遇到问题的部分):demo

function ctrl($scope) {
    $scope.items = ['one','two'];
    $scope.selection = 'two';
    $scope.data = {email:''};
    $scope.$watch('data.email', function (now, then, scope) {
        console.log('email change', now, then);
    });
}

请注意,如果输入为 ,则仅当电子邮件有效时才会触发手表type="email"

编辑:更新为与 ng-switch 一起使用。

说明:正如 miqid 所指出的,当您使用原语时,子作用域无法访问父作用域变量,但当它们是对象时,角度会在子作用域中创建引用。

于 2014-04-08T08:27:07.487 回答