【问题标题】:Angularjs doesn't update scope when calling a function?Angularjs在调用函数时不更新范围?
【发布时间】:2014-10-13 08:45:59
【问题描述】:

我有一个用于我的模态的模态服务,在服务中我传递控制器的范围,以便模态视图可以访问范围对象。当我使用函数更新范围时,值永远不会更新。

我曾尝试使用 $apply,但我得到的错误是摘要循环已在运行。

这里是代码

.controller('LoginCtrl', ($scope, $location, $rootScope, Modal, $log, $http) ->

  $scope.placeholder = {
    email: 'Email Address',
    password: 'password'
  }

  $scope.login = (email, password)->
    $http.post('/dashboard/login', {
      email: email,
      password: password
    }).error((data, status)->
      $scope.invalidPassword = "lalala"
      $scope.$apply()
    ).success (data, status) ->
      $rootScope.userAuth = true
      $rootScope.userInfo = data
      $state.go('dashboard')
      $modalInstance.close()

  Modal.custom("modal-login2.jade",$scope, #here is where I pass the controller's scope as the scope for the Modal
  keyboard: false
  backdrop: 'static'
  )

)

那我的玉

div
  script(type='text/ng-template' id="modal-login2.jade")
    .modal-header
      h3.modal-title Login into Dashboard
    .modal-body
      form(name="loginForm", novalidate).form-horizontal
          .row.alert.alert-danger(ng-show='invalidPassword')
            span(translate) The specified e-mail or password was invalid !
          .row.form-group
            label.col-xs-3.control-label(for='email') E-mail
            .col-xs-9
              input.form-control(required, ng-model='email', type='email', name='email', placeholder="{{ placeholder.email }}")
          .row.form-group
            label.col-xs-3.control-label(for='password') Password
            .col-xs-9
              input.form-control(required, ng-minlength=6, ng-model='password', type='password', name='password', placeholder="{{ placeholder.password }}")
    .modal-footer
      .col-xs-offset-2.col-xs-3
        button.btn.btn-primary(type='submit', translate,
          ng-click='login(email, password)', ng-disabled='loginForm.$invalid || waitText') Sign in

【问题讨论】:

  • 在没有指定时间的情况下使用 $apply 使用 $timeout 效果更好,因为 $timeout 计划在模型上更改以用于下一个摘要而不是强制它 - 这使您的摘要已经处于循环错误中
  • 我应该如何使用 $timeout 来延迟应用或延迟范围变量的更改?
  • 像使用 $appyly 一样使用 $timeout,$timeout(function(){$scope.model = value})
  • 我得到了同样的结果,这样做 DOM 被改变了

标签: javascript angularjs coffeescript pug


【解决方案1】:

因此,当我尝试访问 Modal 的范围时,我需要使用 this 而不是 $scope。

所以不是

$scope.model

我应该使用

this.model

我不完全确定为什么,但我认为这与 Modal 服务有关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    相关资源
    最近更新 更多