【问题标题】:$watch is not working in Modal even though using like $scope.user={pwd1:''}即使使用类似 $scope.user={pwd1:''},$watch 也不能在 Modal 中工作
【发布时间】:2015-10-15 22:08:45
【问题描述】:

请参考我的 Plunker 链接: http://plnkr.co/edit/0vOjw0?p=preview

index.html

    <!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">

    <script src="angular.min.js?version=1.4.2"></script>
    <script src="ui-bootstrap.js"></script>
    <script src="script.js"></script>
  </head>

  <body>




  <div class="col-lg-2" style="margin-right: 7px;float: left;">
      <button ng-controller="registrationCtrl" type="button" class="btn btn-primary btn-responsive" ng-click="openRegistration()"> Registration</button>
  </div>




  </body>

</html>

registration.html

<div class="modal-dialog" id="registration.html">


        <div class="modal-body">

            <form name="form" class="css-form" novalidate>



                <label for="pw1">Password:</label>
                <input type="password" id="pw1" name="pw1" ng-model="user.pw1" ng-required="" />
                <div>{{user.pw1}}</div>


            </form>

        <div class="modal-footer">

            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </div>
</div>

script.js

angular.module('app',['ui.bootstrap']).controller('registrationCtrl', ['$scope','$modal',function ($scope, $modal)
    {

        $scope.openRegistration = function ()
        {
            //console.log("inside openLogin");
            var modalInstance =$modal.open(
                {
                    templateUrl: 'registration.html',
                    controller: 'registrationPopupController',
                    backdrop: 'static',
                    keyboard: false,
                    size: 'sm'
                });
            //console.log("done open")
        }
    }]).controller('registrationPopupController', ['$location','$scope','$modalInstance',function ($location,$scope,$modalInstance,LoginService)
    {

        $scope.user={
            pwd1:''
        };
        $scope.$watch('user.pwd1',function(newV,oldV){
          if(newV!=oldV){
          alert(newV)
            console.log(newV,oldV);
          }

        },true);


        $scope.cancel = function ()
        {
            $modalInstance.dismiss('cancel');
            location.href='#/';
        };

    }]);

我面临的问题是在密码文本框中写入时,我的 $watch 不会在模态实例控制器中调用。但是当我在同一个简单的控制器中编写它时它会起作用,请帮帮我!

【问题讨论】:

  • 不确定是否是这种情况,但是您正在 $watch 上运行不是范围变量的东西。 user 是范围变量,user.pw1 不是。它是一个对象的一个​​属性,恰好是一个变量

标签: javascript angularjs angularjs-scope angular-ngmodel angularjs-watch


【解决方案1】:

这是您的 ng-model 值中的错字,应该是 user.pwd1 而不是 user.pw1

标记

<input type="password" id="pwd1" name="pw1" ng-model="user.pw1" ng-required="" />

Working Plunkr

【讨论】:

  • @intellect_dp 你能投票吗?很高兴能帮助你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 2021-11-13
  • 2011-11-20
  • 2021-12-30
相关资源
最近更新 更多