/angularjs/

AngularJS - JSON Menu Example

2014-05-14 00:09:43

Example: https://github.com/szalek/AngularJS-JSON-Menu-Example

app.js

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

app

    .controller("NameCtrl", function ($scope) {
        $scope.hello = "Welcome welcome!";
    })

    .controller("NameCtrl2", function ($scope) {
        $scope.hello = "Welcome welcome! 2";
    })

    .directive('btbwMenu', function () {
        return {
            controller: function ($scope, $http) {
                $http.get('menu.json').success(function (data) {
                    $scope.menu = data;
                    $scope.submenu = data[0].sub;
                });
                $scope.changeSub = function (menuId) {
                    $scope.submenu = $scope.menu[menuId].sub;
                }
            },
            restrict: 'E',
            templateUrl: 'tpl/menu.tpl.html'
        };
    });
;

index.html


<html ng-app='"szalekApp"'>
<head>
<meta charset="utf-8"/>
<title>Angular.js Example</title>
<script src='"angular.min.js"'></script>
<script src='"app.js"'></script>
</head>
<body>
<btbw-menu></btbw-menu>
<section ng-controller='"NameCtrl"'>
<h1>{{hello}}</h1>
</section>
<section ng-controller='"NameCtrl2"'>
<h1>{{hello}}</h1>
</section>
</body>
</html>

/tpl/menu.tpl.html


<nav>
<a href='"#"' in="" menu&quot;="" ng-click='"changeSub(item.id)"' ng-repeat='"item'>{{item.name}}</a>
<hr/>
<a href='"#"' in="" ng-repeat='"item' submenu&quot;="">{{item.name}}</a>
</nav>

menu.json

[
    {
        "id": "0",
        "name": "Item-1",
        "sub": [
            {"name": "SItem 1-1"},
            {"name": "SItem 1-2"},
            {"name": "SItem 1-3"},
            {"name": "SItem 1-4"}
        ]
    },
    {
        "id": "1",
        "name": "Item-2",
        "sub": [
            {"name": "SItem 2-1"},
            {"name": "SItem 2-2"},
            {"name": "SItem 2-3"},
            {"name": "SItem 2-4"}
        ]
    },
    {
        "id": "2",
        "name": "Item-3",
        "sub": [
            {"name": "SItem 3-1"},
            {"name": "SItem 3-2"},
            {"name": "SItem 3-3"},
            {"name": "SItem 3-4"}
        ]
    },
    {
        "id": "3",
        "name": "Item-4",
        "sub": [
            {"name": "SItem 4-1"},
            {"name": "SItem 4-2"},
            {"name": "SItem 4-3"},
            {"name": "SItem 4-4"}
        ]
    }
]