Chrillewoodz
Chrillewoodz

Reputation: 28318

How to properly update a scope variable if it's being passed as a parameter

I'm trying to pass a scoped object property into a function in my controller and then change its value to either true or false depending on the current value. Then I want this value to be updated in the scope at the same time.

The problem that occurs is that I can't just use $scope.isBeingEdited in the function to update the scope, because it's present in an ng-repeat so it wouldn't know which one to update. And just setting the value of the parameter doesn't seem to update the scope.

I read this question which seems to state that this is not possible? Maybe I read it wrong but surely there must be a rather simple way of achieving this? This is causing me problems on more than one front so it's time that I solve this issue.

Here's a dumb version of my markup, containg a title, an input and an edit "button":

<div ng-repeat="bodypart in body">
  <h3 ng-hide="bodypart.isBeingEdited" ng-bind="bodypart.name"></h3>
  <input ng-show="bodypart.isBeingEdited">
  <span ng-click="setEditState(bodypart.isBeingEdited)">Edit</span>
</div>

When I click on "edit" then this should run, passing bodypart.isBeingEdited as the variable to do a value check for:

$scope.setEditState = function(item) {

  // Check if item is true or false
  // and set it accordingly
  item ? item = false : item = true;
}

How can I ensure that the scoped variable that gets passed to this function gets updated when item gets updated?

Upvotes: 0

Views: 121

Answers (2)

Travis
Travis

Reputation: 5061

Since objects are passed by reference, you should be able to do something like this.

<div ng-repeat="bodypart in body">
  <h3 ng-hide="bodypart.isBeingEdited" ng-bind="bodypart.name"></h3>
  <input ng-show="bodypart.isBeingEdited">
  <span ng-click="toggleBodyPartState(bodypart)">Edit</span>
</div>

$scope.toggleBodyPartState = function(bodyPart) {
    bodyPart.isBeingEdited = !bodyPart.isBeingEdited;
}

Upvotes: 0

dotnetom
dotnetom

Reputation: 24901

You can pass item instead of property isBeingEdited and use it in code accordingly:

<span ng-click="setEditState(bodypart)">Edit</span>

Controller

$scope.setEditState = function(item) {
  item.isBeingEdited = !item.isBeingEdited;
}

Upvotes: 2

Related Questions