0

I want to create a method in my controller to set to null different variables from my controller $scope. So I've this in my controller :

FootCreator.controller('FooController', function($scope) {
    $scope.zoo = {
        id: 1,
        name: 'Lorem',
    };

    $scope.foo = {
        id: 2,
        title: 'bar',
    };

    $scope.deleteProperty = function(property) {
       property = null;
    };
});

And in my HTML I call it this way (for example) : <a ng-click="deleteProperty(zoo)" class="remove icon-remove" title="Remove"></a>

When I console.log() the $scope.zoo it's not set to null. I think I must do something bad but can't find what. I try to do that not to have a deleteZoo(), deleteFoo() etc.

Thanks for the help/tips !

1 Answer 1

3

In your deleteProperty method, you are just setting the property parameter to null and this is never going to have any effect on your scope.

A simplified example of what you're doing here is:

$scope.zoo = { id: 1, name: 'Lorem' };
var property = $scope.zoo;
property = null;
console.log($scope.zoo);  // previous line had no effect on $scope.zoo

I would suggest passing the property name as a string instead of the property itself. Then you can do this:

$scope.deleteProperty = function(property) {
   delete $scope[property];
};
<a ng-click="deleteProperty('zoo')" class="remove icon-remove"
   title="Remove"></a>

If you really want to pass the property itself (like you're doing in your HTML), you'd need to loop through all the properties to find the one that matches:

$scope.deleteProperty = function(property) {
   for (var p in $scope) {
       if ($scope.hasOwnProperty(p) && $scope[p] === property) {
           delete $scope[p];
       }
   }
};
Sign up to request clarification or add additional context in comments.

2 Comments

So if I understand what your mean, when I do ng-click="deleteProperty(zoo)" and then getting the zoo object in my controller method I'm not working on the actual $scope.zoo but on a reference copy ?
@Mushr00m In this scenario $scope.zoo is a reference to some object, and property is also a reference to that same object. In the line property = null, you are changing property to refer to null instead of that object. $scope.zoo will continue to refer to that object. That's how references work in JavaScript. Please see the example I added above at the beginning of my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.