Delete property from scope variable

28.4k views Asked by At

I have a scope variable $scope.object = { prop: 12345 } whose properties I delete with setting them to undefined.

<button ng-show="object.prop" ng-click="object.prop = undefined"/>

Is there a possibility to delete a properties from within a template and without an additional function in the controller instead of setting their values to undefined?

5

There are 5 answers

6
Giwwel On

Yes... I.e. that you can change the value of the variable ... Maybe it will be a help for you

try this:

 <button ng-show="object.prop" ng-click="object.prop = 'undefined'"/>

or you can clear the value...

 <button ng-show="object.prop" ng-click="object.prop = ''"/>

also you can set the value to null

 <button ng-show="object.prop" ng-click="object.prop = null"/>
2
Kalhan.Toress On

use codes below to delete a property from a object

In HTML

<button ng-show="object.prop" ng-click="deleteProperty()" />

In Controller

$scope.deleteProperty = function() {
    delete $scope.object.prop;
}    
0
Amir On

Here's the way that you can delete any property name from the object of scope. This method require using Underscore.js library.

index.html

//Underscore.js must be imported
<script src="path/to/underscore/underscore-min.js"></script>

//Replace prop with any property name
<button ng-click="removeMyProperty(object, 'prop')">Test</button> 

Controller

$scope.object = {"prop": "test", "anotherProp" : 10};
$scope.removeMyProperty = function(variable, propName){
    var keys = _.keys(variable);
    _.each(keys, function(data){
        if(data === propName){
            $scope.object = _.omit(variable, propName);
        }
        else {
            console.log("No such property name in array!");
        }
    });
};

This works only when you use Underscore.js library and thus you must add it to your project classpath and import underscore.js file in index.html

If you are not familiar with Underscore, please go here Underscore.js

0
Andrew Clavin On

If the object is always at a point that you know what properties it would have besides the one you are deleting you could try something like:

<button ng-show="object.prop" ng-click="object = {otherProp1: object.otherProp1, otherPropN: object.otherPropN}"/>
0
Goran Antić On

I think that you can't do that. I tried using "delete" operator, something like ng-click="delete object.prop". But it turns out that AngularJS expressions are limited and this gives me a $parse error while compiling the template, so you would have to write that in controller in order to completely delete it, unfortunately.

But if you want to avoid the controller at all means, setting the property to undefined might be a better idea, read the answer by Dan in this question: How do I remove a property from a JavaScript object?