Remove property from scope variable

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 it possible to remove properties from a template without an additional function in the controller instead of setting their values ​​to undefined ?

+5
source share
5 answers

use codes below to remove property from object

In HTML

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

In the controller

 $scope.deleteProperty = function() { delete $scope.object.prop; } 
+10
source

Yes ... Ie that you can change the value of a variable ... Perhaps this will help you

try the following:

  <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"/> 
0
source

Here you can remove any property name from the scope object. This method requires the use of the 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 only works when using the Underscore.js library, and therefore, you must add it to your project path and import the underscore.js file into index.html

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

0
source

If the object is always at a point at which you know what properties it would have besides the one you delete, you can try something like:

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

I think you cannot do this. I tried using the delete operator, something like ng-click="delete object.prop" . But it turns out that AngularJS expressions are limited, and this gives me a parsing error when compiling the template, so you have to write this in the controller to unfortunately completely remove it.

But if you want to avoid the controller altogether, setting the property to undefined might be a better idea, read Dan's answer in this question: How can I remove a property from a JavaScript object?

0
source

Source: https://habr.com/ru/post/1207664/


All Articles