$ scope变量更改时数据绑定不更新

时间:2017-12-02 20:51:19

标签: javascript angularjs data-binding

我有一个登录表单,其可见性与变量绑定。我在表单中有一个链接,根据用户是登录还是注册来更改文本。退出表单后,我将表单重置为isOnLoginForm,以更新注册文本。问题是,范围变量更改但注册文本没有 - 它在单击注册按钮时更新,但在隐藏表单时不会更新。

这是控制器:

angular.module('DataStructureVisualizer').
controller("RegLoginController", function($scope, $rootScope) {

  //Show / hide login form
  $scope.toggleRegLoginForm = function() {
    $rootScope.RegLoginForm.showForm = ! $rootScope.RegLoginForm.showForm;

    if($rootScope.RegLoginForm.showForm == true) {
      $rootScope.RegLoginForm.isOnLoginForm = true;
    }

    updateRegistrationText();
  }

  $scope.isRegLoginFormShown = function() {
    return $rootScope.RegLoginForm.showForm;
  }

  //Updating form to be registration
  updateRegistrationText();

  function updateRegistrationText() {
    $scope.registrationText = $rootScope.RegLoginForm.isOnLoginForm ? 'Need to create an account?' : 'test';    
    console.log($scope.registrationText);
  }

  $scope.switchToRegistration = function() {
    $rootScope.RegLoginForm.isOnLoginForm = false;
    updateRegistrationText();
  }
});

以下是观点:

<div id="RegLoginBlackout" ng-controller="RegLoginController" ng-show="isRegLoginFormShown()" ng-click="toggleRegLoginForm()"></div>
<div id="RegLogin" ng-controller="RegLoginController" ng-show="isRegLoginFormShown()"> 
  <span>Please log in</span>
  <br />
  <form>
    <input type="text" name="username" value="username" 
      onfocus="this.value = this.value=='username'?'':this.value;" 
      onblur="this.value = this.value==''?'username':this.value;">
      <br>
    <input type="password" name="password" value="password" 
      onfocus="this.value = this.value=='password'?'':this.value;" 
      onblur="this.value = this.value==''?'password':this.value;">
    <br>
    <input type="button" name="login" value="Login">
  </form>
  <a href="" ng-click="switchToRegistration()">{{registrationText}}</a>
</div>

$scope.registrationText正在正确更新,但数据绑定未使用它进行更新。只要用户交互正确,就应该在视图上调用$ digest?那么为什么我单击注册链接时会正确更新,而不是再次单击登录表单时更新?

0 个答案:

没有答案