Dad85
Dad85

Reputation: 33

Remove dynamic div with Angular

I'm trying to remove a div dynamically added by clicking on the remove button. I've created this fiddle https://jsfiddle.net/y4punqp3/2/ for convenience.

The remove function

$scope.removeUnavailability = function () {
    --numUnavail;
    document.getElementById("tempUnavail").remove();
}

The corresponding line should be deleted when clicking on the remove button. What am I missing?

Upvotes: 0

Views: 1123

Answers (1)

Fissio
Fissio

Reputation: 3758

Check the updated fiddle for a clean solution: https://jsfiddle.net/y4punqp3/5/

In Angular, you want to have the data in your controller represent the model, and your template to draw stuff based on that model. You don't want to manually add/remove HTML or edit the DOM in any way outside of directives, otherwise you're just shooting yourself in the foot and you're not really using angular in any meaningful way.

JS:

var app = angular.module("satUnav-app", []);
app.controller("satUnav-ctrl", function($scope) {

  $scope.unavailabilities = [];

  $scope.addUnavailability = function () {
    $scope.unavailabilities.push({});
  }

  $scope.removeUnavailability = function (idx) {
    $scope.unavailabilities.splice(idx, 1);
  }
});

HTML:

<div ng-repeat="unavail in unavailabilities">
    <select ng-model="unavail.selection">
        <option>PRN 01 (ID:401)</option>
        <option>PRN 02 (ID:402)</option>
        <option>PRN 03 (ID:403)</option>
        <option>PRN 04 (ID:404)</option>
    </select>
    <label for="tempUnavail">Start</label>
    <input type="datetime-local" ng-model="unavail.start">
    <label for="tempUnavail">Stop</label>
    <input type="datetime-local" ng-model="unavail.stop">
    <button type="button" data-ng-click="removeUnavailability($index)">Remove</button>
</div>

Now we have nice and clean Angular code where it's easy to add/remove divs just by editing the array scope variable based on which the view is drawn - none of that silly DOM manipulation.

EDIT: And as always in these jQuery-Angular questions, check out the answer here: https://stackoverflow.com/a/15012542/3368834

Upvotes: 1

Related Questions