Reputation: 4517
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
?
Upvotes: 6
Views: 28546
Reputation: 450
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?
Upvotes: 0
Reputation: 574
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}"/>
Upvotes: 0
Reputation: 1061
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
Upvotes: 0
Reputation: 347
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"/>
Upvotes: 0
Reputation: 21901
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;
}
Upvotes: 12