javascriptangularjssaveangularjs-ng-disabled

angularJS : disable link based on variable value, and display message box


I am struggling to figure out how to disable a ng-click event based on the value of a boolean variable.

I have a form, on which the user has to click a (+) sign/ link to add a new record, when the user does this, a small function is triggered, and sets a boolean to false.

Code:

vm.addNewRecord = function (formClass) {
    vm.hasID = false;
};

The form has an icon/ link that allows the user to save information about participant, to the record.

Code:

<div class="icon">
    <a ng-click="addParticipants(data)">
        <i class="fa fa-fw fa-plus"></i>
    </a>
</div>                        

That issue is that this information depends on a record id, but this id does not exist yet.

I need to be able to disable the ng-click of: addParticipants(data) is the value of hasId = false, and at the same time (somehow) allow the user to click it to display a message in the lines of: "Please save this record before adding participants."

What I have tried so far, and without success:

<div class="datagrid-icon">
    <a ng-click="datagrid.add(datagrid)" ng-disabled="!hasID">
        <i class="fa fa-fw fa-plus"></i>
    </a>
</div>

And:

<div class="datagrid-icon">
    <a ng-click="datagrid.add(datagrid)"  ng-class="{'disabled': !hasID}">>
        <i class="fa fa-fw fa-plus"></i>
    </a>
</div>

I checked the value of hasID and it is false but I am still able to click on the (+) sign for addParticipants. And also, I am not sure how if I manage to disable the click, I am going to display the message instructing the user to first save the main record and then adding participants will be possible.

If anyone could offer some help to resolve this, that would be much appreciated.

Thank you.


Solution

  • To disable a link you can do like

    <a ng-click="hasID && datagrid.add(datagrid)">
        <i class="fa fa-fw fa-plus"></i>
    </a>
    

    But it's much better to have a method inside your controller like

    vm.addToGrid = function(id) {
        if (id) {
        $scope.datagrid.add(id);
      } else {
        alert('Save the record before');
      }
    }
    
    <a ng-click="vm.addToGrid(datagrid)">
        <i class="fa fa-fw fa-plus"></i>
    </a>