简体   繁体   中英

How to set new value of the Angular directive “ng-init” depending on the value of a <select> dropdown box?

So I want to set a value for ng-init if a specific option is selected. If that specific option is not selected yet, or is changed away from, I'd like to delete the ng-init value.

<select id="exSelect" onchange="checkButton()">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

<textarea type="text"
    class="form-control"
    ng-model="vm.request.description"
    name="description" id="description"
    rows="10" placeholder="Must be atleast 50 characters."
    ng-minlength="50"
    required>
</textarea>
function checkButton()
{
    var dropdownValue = document.getElementById("exSelect");
    if (dropdownValue.value == "3") {
        //Why does this not work?
        document.getElementById("description").ng-init = 'Example attribute setting';
    } else {
        document.getElementById("description").ng-init = '';
    }
}

This code is super simplified example version of what I am working on right now, but overall a similar idea of what I am trying to do as a small part of a much larger program. So I would like for the checkButton() function to run each time a new option is selected. If 3 is selected, I would like the if statement to execute and set the "ng-init" attribute of the element with the Id of "description" as the text in the function. If another option is selected, I would like for the checkButton() function to run again and it will set the the ng-init attribute as empty.

First use the ng-model and ng-change directives:

<select id="exSelect" ng-model="vm.sel1" ng-change="vm.checkButton()">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Then in your controller:

vm.checkButton = function() {
    if (vm.sel1 == "3") {
        vm.request.description = 'Example attribute setting';
    } else {
        vm.request.description =  = '';
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM