在Angular中模态关闭时设置复选框值

时间:2015-03-11 07:45:54

标签: angularjs angular-ui-router

我想在模态关闭时自动检查复选框。我使用一个控制器用于模态,另一个控制器用于主页面。以下代码不起作用。我是否需要使用指令才能完成此任务,还是有其他方法?

HTML - 主页:

<label>
  <input type="checkbox" ng-model="agreementForm.value1"> I agree.
</label> 

HTML - 模态:

<div class="modal-footer">
 <button ng-click="agreementForm.cancel()" class="btn btn-warning">Cancel</button>
  <button ng-click="agreementForm.agree()" ng-disabled="agreementForm.$invalid" class="btn btn-primary" >I agree</button>
</div>

控制器的Javascript:

myApp.controller('AgreementFormCtrl', function ($location, $stateParams, $modalInstance) {
  var agreementForm = this;
  agreementForm.cancel = function () {
  $modalInstance.dismiss('cancel');
};

agreementForm.agree = function() {
  agreementForm.value1=true;
  $modalInstance.close(agreementForm.selected);
});

myApp.controller('ContactFormCtrl',
   function ($location, $stateParams, Contacts) {
     var contactForm = this;
  });
   contactForm.save = function () {
     Contacts.$add(contactForm.contact).then(function (data) {
       $location.path('/');
     });
   };

Modal的路由器:

.state('payment.agreement', {
url: '/agreement',
onEnter: ['$stateParams', '$state', '$modal', function ($stateParams, $state, $modal) {
   $modal.open({
       templateUrl: 'views/agreement.html',
       controller: 'AgreementFormCtrl as agreementForm'
      }
    )
      .result.finally(function () {
        $state.go('^');
      });
  }]
})

1 个答案:

答案 0 :(得分:1)

您可以使用$rootScope来做到这一点,而且您错过了初始化$scope

  

首先,您需要在复选框

中添加ng-checked指令
 <input type="checkbox" **ng-checked="agreementForm.IsChecked"**
  ng-model="agreementForm.value1"> I agree.
  

然后您需要初始化rootscope

中的controller

myApp.controller('AgreementFormCtrl', function ($location, $stateParams, $modalInstance,**$rootScope,$scope**) { //code };

  

最后,当模态关闭时,您可以为已检查对象赋值

$scope.agreementForm.cancel = function () {
  $modalInstance.dismiss('cancel');
$rootScope.agreementForm.IsChecked="Checked";//True or false
};