AngularJS - Why is the DOM not updating

user884542

So, what I am trying to do is add a "stack" - a basic JS object - into an array called cardStacks, declared the stackCtrl function. I've read that the controller in AngularJS is not supposed to do very much, nor do you want the manipulation of DOM elements done the controller. So what I have done is create a "save" directive which, as you could probably guess, adds a new "stack" into $scope.cardStacks (if the object is not being edited)

Everything seems to work ok, up until when the template is supposed to update. console.log() reveals that objects are going into an array, but because the template is not being updated, I can only guess it is not $scope.cardStacks.

Can somebody give the following a look and tell me why the template is not listing the "stacks" in the template?

Consider the following:

Template:

<div ng-controller="stackCtrl">
    <stackeditor></stackeditor>
    <p>Stacks:</p>
    <ul class="stack-list" ng-repeat="stack in cardStacks">
        <li><a href="#">{{stack.title}}</a>
            <span class="stack-opts"> (<a href="#" ng-click="edit=true">Edit</a> | <a href="#">Delete</a>)</span>
        </li>
    </ul>
</div>

Template for the stackeditor tag/directive:

<div>
    <span class="button" ng-click="show=!show">+ New</span>
    <form ng-show="show" novalidate>
        <input type="text" ng-model="stackTitle" required/>
        <button class="button" save>Save</button>
        <button class="button" reset>Cancel</button>
        <div ng-show="error"><p>{{error}}</p></div>
    </form>
</div>

Controller:

function stackCtrl($scope) {
    $scope.cardStacks = [];
    $scope.stackTitle = "";

    $scope.addStack = function(title) {
        var newStack = {};
        newStack.title = title;
        $scope.cardStacks.push(newStack);
    }

    $scope.removeStack = function($index) {
        console.log("removing Stack...");
    }

    $scope.editStack = function(element) {
        console.log("editing Stack...");
    }
}

Directive:

fcApp.directive('save', function() {
    var linkFn = function($scope, element, attrs) {
        element.bind("click", function() {
            if (typeof $scope.stackTitle !== 'undefined' && $scope.stackTitle.length > 0) {
                if ($scope.edit) {
                    $scope.editStack(element);
                } else {
                    $scope.addStack($scope.stackTitle);
                }
            } else {
                $scope.error = "Your card stack needs a title!";
            }
        });
    });

    return {
        restrict: "A",
        link: linkFn
        }
    }
});
Alagarasan M

Try using $apply:

 $scope.cardStacks.push(newStack);
 $scope.$apply(function(){
   $scope.cardStacks;
 }

Rendering might be the problem..... Hope it helps.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related