Reputation: 79
I am playing around with angularjs and I am attempting to build a menu tree. In my current example my ng-repeat is not working and {{folder.name}} does not display the array of folders, which is instantiated so there is at least one folder object in the array. Any ideas?
Here is a link to the plunker with the output: http://plnkr.co/edit/j7J9ibpqgt65jdGSsPWu
My angular code:
var treeApp = angular.module("treeApp", [])
.controller("treeController", ["$scope", function($scope) {
var defaultName = "Node";
//Node object
function Folder() {
var name = defaultName;
}
//Node array
$scope.menu = [
this.folder1 = new Folder()
];
//Adds node to array
$scope.add = function() {
var newFolder = new folder();
$scope.menu.push(newFolder);
};
//Removes last node in array
$scope.remove = function() {
$scope.menu.pop();
};
}])
My html:
<!DOCTYPE html>
<html lang="en" ng-app="treeApp">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="style.css" />
</head>
<body ng-controller="treeController">
<div>
Name of Nodes: <input type="text" ng-model="defaultName" placeholder="Data">
</div>
<div class="Tree Display">
<hr/>
<h2><strong>The Tree:</strong></h2>
<button ng-click="menu.add()">Add</button>
<br/>
<button ng-click="menu.remove()">Remove</button>
<ul>
<li ng-repeat="folders in menu">
{{folder.name}}
</li>
</ul>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="ngTree.js"></script>
</body>
</html>
Upvotes: 1
Views: 238
Reputation: 5408
There are a couple of issues I see. First, Dalorzo is right that you need to bind the name variable to the actual function with:
//Node object
function Folder() {
this.name = defaultName;
}
Also, in your repeat, you're calling folders in menu
which should map to folders.name
instead of folder.name
. In this case folders != folder.
Lastly, you're binding your events to the menu object in your ngclick, so you need to bind them in your JS also like:
$scope.menu.add = function() { }
$scope.menu.remove = function() { }
That's all I see for now though, so that should work.
Upvotes: 1
Reputation: 20014
Change this:
//Node object
function Folder() {
var name = defaultName;
}
With this:
//Node object
function Folder() {
this.name = defaultName;
}
In the first example name
is only a variable and not a property of Folder.
Additionally I think this code is invalid:
$scope.menu = [
this.folder1 = new Folder()
];
An array in Javascript will be like this:
$scope.menu = [ new Folder(), new Folder() ];
Upvotes: 2