K. Gaud
K. Gaud

Reputation: 3

My function in my controller works but does not update the view (Angularjs)

I've some fields, they can be edited. The user can cancel the edition mode with the button 'Cancel':

<button ng-click="cancelEdit();" ng-show="editable">
    <i class="fa fa-remove"></i> Cancel
</button>

The event ng-click call the function cancelEdit().

$scope.cancelEdit = function(){
    $scope.editable=false;
    $scope.jobNameInput = $scope.jobToView.name;
    $scope.selectedPriority = $scope.jobToView.priority;
    $scope.jobCommentsInput = $scope.jobToView.comments;
}

In this function, I just want to set the boolean variable for edition mode to false and reinit the values of my inputs to the default value (before edition mode). After this function is calling, the values are updated for the controller, but not in my view:

<button ng-click="editable=true;" ng-show="!editable">
    <i class="fa fa-edit"></i> Edit
</button>

This button is shown when the variable editable is set to false. So when I click on the cancel button, theoretically, the button Edit must be shown and my inputs should be updated. Why is this not the case ?

Upvotes: 0

Views: 88

Answers (2)

K. Gaud
K. Gaud

Reputation: 3

Thanks to Korte for the answer on the boolean variable. To complete, with regard to the inputs, I found the answer to my question. Simply declare in the controller:var vm = this;;

And simply, in the model of the input, write: ng-model="vm.jobCommentsInput"

I think so the inputs are considered as my boolean variable and they needs to be objects.

Upvotes: 0

korteee
korteee

Reputation: 2682

Primitives are immutable – i.e. its value cannot be changed by invoking functions on it.

Your $scope.editable is a boolean variable which is primitive. That's why the view does not get updated. Its value gets changed only in the closure of your function.

To apply it in your view you should change it to a non primitive value. This could be done if you set it as a property of an object.

E.g.

$scope.isEditable = {
  value:false
}

Then play around with that object. In your case:

Cancel button:

<button ng-click="cancelEdit();" ng-show="isEditable.value">
    <i class="fa fa-remove"></i> Cancel
</button>

Edit button:

<button ng-click="isEditable.value=true;" ng-show="!isEditable.value">
    <i class="fa fa-edit"></i> Edit
</button>

Function:

$scope.cancelEdit = function(){
    $scope.isEditable.value = false;
    $scope.jobNameInput = $scope.jobToView.name;
    $scope.selectedPriority = $scope.jobToView.priority;
    $scope.jobCommentsInput = $scope.jobToView.comments;
}

Upvotes: 1

Related Questions