Amber Lee Amber Lee - 2 months ago 8
Javascript Question

AngularJS - how to add a conditional to bootstrap modal target?

So I have a modal that appears when a button is clicked - however I want the modal ONLY to appear when certain conditions are met (which are defined in my controller).

HTML CODE:

<button class="btn btn-primary-outline" type="button" data-uk-modal="{target:'#previewModal'
}" ng-click="previewOfferBefore()">Preview</button>


The above works (modal with the id 'previewModal' pops out on click). So my approach is to add the conditional in the controller and define the value of the "target" in there using Angular data binding.

ie:

<button class="btn btn-primary-outline" type="button" data-uk-modal="{target: {{ previewLink
}}}" ng-click="previewOfferBefore()">Preview </button>


Then the controller would have:

$scope.previewOfferBefore = function() {
if (/*some conditions here*/) {
$scope.previewLink = '#'; /*don't let a modal pop up */
}
else {
$scope.previewLink = '#previewModal' /*let the modal pop up */
}
}


One approach I tried as well is using ng-href instead of bootstrap's data-uk-modal and that also didn't work. I know my controller function is fine since when I place {{ previewLink }} inside a p html tag it prints out the right id I want. So the issue is how I'm binding the data inside the button class.

Answer

If you're okay with the button being disabled or greyed out, then one solution would be to use ng-disabled. Your controller would look something like this;

$scope.previewOfferBefore = function() {
if (/*some conditions here*/) {
     $scope.canClick= true;
 }
else {
     $scope.canClick= false;
 }
}

and your html would then become;

 <button ng-disabled="canClick" class="btn btn-primary-outline" type="button" data-uk-modal="{target:'#previewModal'
 }" ng-click="previewOfferBefore()">Preview</button>

Then your button will become unclickable if it hits the false case on the if statement.