ps0604 ps0604 - 4 months ago 21
AngularJS Question

Check box not changing state in Angular UI Modal

In this plunk I have an Angular UI modal window with a checkbox button.

The problem is that the checkbox doesn't change its state when it is clicked.

Try clicking on the button multiple times, you will see an alert showing the state that never changes. How to fix this?

Javascript:

var app = angular.module('app', ['ui.bootstrap']);
app.controller('ctl', function ($scope,$uibModal) {
});


app.directive('buttondir', function ($uibModal) {

var directive = {};

directive.restrict = 'EA';

directive.scope = true;

directive.templateUrl = "buttondir.html"

directive.link = function (scope, element, attrs) {


scope.modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
scope: scope,
windowClass: 'app-modal'
});

scope.singleModel = 1;

scope.onclick = function(){
alert(scope.singleModel)
};
};



return directive;

});


HTML:

<script type="text/ng-template" id="myModalContent.html">

<div class="modal-header">
<h4 class="modal-title">The Title</h4>
</div>

<button type="button" class="btn btn-primary" ng-model="singleModel" uib-btn-checkbox
btn-checkbox-true="1" btn-checkbox-false="0" ng-click="onclick()"> Single Toggle </button>

</script>

Answer

Never assign ngModel directly to $scope.

Always always use Dot Rule or controller-as-syntax.

scope.model = {};
scope.model.singleModel = 1;

scope.onclick = function() {
  alert(scope.model.singleModel)
};

<button type="button" class="btn btn-primary" ng-model="model.singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0" ng-click="onclick()"> Single Toggle </button>

DEMO