Zze Zze - 1 month ago 13
AngularJS Question

Update ng-repeat on data change

I am currently learning AngularJS.

I am stuck trying to update a series of buttons which I have generated from a directive when the object data is updated.

I have read a number of posts addressing similar issues for where data not created in a directive won't update to no avail.

HTML

<body>
<div id="application" data-ng-app="ApplicationDirective" ng-controller="ApplicationController" class="container-fluid">
<side-panel class="col-lg-2"></side-panel>
<div ng-controller="HomeController" class="content col-lg-10">

</div>
</div>
</body>


As you can see I have defined 2 controllers. 1
ApplicaitonControler
to manage the application as a whole and then a second
HomeController
to manage an inner section of the HMTL.

I then have a directive which generates a series of buttons for a side panel.

var app = angular.module('ApplicationDirective', []);

app.directive("sidePanel", function() {
return {
restrict: "E",
template : "<div>" +
"<input ng-repeat='btn in sidePanelButtons' type='button' value={{btn.value}}>" +
"</div>"
};
});


The
$scope
data for the above is defined in the
ApplicationContoller
. Then I update the data in
HomeController
.

app.controller("HomeController", function($scope) {
$scope.sidePanelButtons = $scope.sidePanelButtons.concat([
{value:"TEST"}
]);
});


At this point, if I log the sidePanelButtons var then I can see that the data was successfully appended, however nothing in the HTML changes?.

I have tried using the $scope.$apply method however I get an error.

Potentially I have the wrong design methodologies, so any help would be appreciated.

T J T J
Answer Source

The concat() method returns a new array.

So when you do

$scope.sidePanelButtons = $scope.sidePanelButtons.concat([
    {value:"TEST"}
]);

You're creating a new sidePanelButtons property in HomeController scope, breaking the reference to sidePanelButtons array in ApplicationController scope. Your side panel directive is watching ApplicationController scope which remain un-altered.

Do $scope.sidePanelButtons.push() instead.