olivierGrech olivierGrech - 8 months ago 18
AngularJS Question

Disabling/Enabling html elements with AngularJS

I'm starting to learn AngularJS for a web app, and I have an issue with understanding the workflow of the framework.

I have 2 dropdowns :

<select class='selectorDropdown' ng-model='selectedElement' ng-change='selectedElementChange()'>
<option value='0' disabled selected>Option0
<option value='1'>Option1
<option value='2'>Option2

<select class='selectorDropdown' id='selector2' disabled>
<option value='3'>Option1
<option value='4'>Option2

I want the second dropdown to be enabled only after another option than Option0 has been selected on the first dropdown. So here's my Javascript code :

$scope.selectedElementChange = function() {
document.getElementById('selector2').disabled = true;

So far, it looks like regular Javascript (and I'm manipulating the DOM), so I guess this is not really the way AngularJS was mean to be used. Could someone help me understand the "correct" way to do this with AngularJS ?


Something like this should work, without writing a single line of JavaScript:

<select class='selectorDropdown' id='selector2' ng-disabled='selectedElement == "0"'>
    <option value='3'>Option1
    <option value='4'>Option2

You don't need the ng-change either. Angular takes care of updating the model when the first selector changes, and then runs a digest loop to update anything else.

You also need to initialize selectedElement somewhere; Angular doesn't take its value from the fact that you wrote selected on the Option0 element. The cleanest way is to do it in the controller:

$scope.selectedElement = "0";

The quick and dirty way is ng-init:

<select ... ng-init='selectedElement = "0"'>