I have the following problem to solve:
From within local menu (menu on the left) I can choose sub pages. Typical scenario. And now I would like to relaod content associated with local menu item. In pure Angular I don't know a standard easy way to achieve it. I could get markup from the server manually and replace the content area manually. Is there a better way? I googled and came across
https://github.com/angular-ui/ui-router
Yet before I start delving into details perhaps you could advice how to solve this problem. Or even advice if I can solve this issue with ui-router.
You want to use nested states in with ui-router. Something like this
$stateProvider
.state('home', {
templateUrl: 'views/home.html',
url: '/home',
controller: 'homeCtrl'
})
.state('home.localmenu1', {
templateUrl: 'views/localmenu1.html',
url: '/home/local1',
controller: 'local1Ctrl'
})
.state('home.localmenu2', {
templateUrl: "views/localmenu2.html",
url: '/home/local2',
controller: 'local2Ctrl'
})
.state('products', {
templateUrl: 'views/products.html',
url: '/products',
controller: 'productsCtrl'
})
So inside your "views/home.html" you can put an element with the ui-view
directive. Then this element will contain the views of the sub-states (home.localmenu1
, home.localmenu2
).
Somewhat similar to kseb's answer, if you prefer to use out-of-the-box Angular, you can use ng-include for this. By attaching a controller you can change what you want shown there as easily as you can for any other "real" view.
If you create a menu.html file in your /views:
<li ng-repeat="menu in menus">
<a href="{{menu.link}}">{{menu.name}}</a>
</li>
You can include it in your index.html like this:
<body>
<ul ng-include="views/menu.html" ng-controller="MenuCtrl"></ul>
<div class="container" ng-view></div>
</body>
That does the trick and is fully valid, works in all browsers. The controller can be just like any other controller you might use.
For local menus where URL bar is not important I often use ng-include
without ng-view
:
<script id="view1" type="text/ng-template">
<div ng-controller="View1Ctrl">
Hello view1.
</div>
</script>
<script id="view2" type="text/ng-template">
<div ng-controller="View2Ctrl">
Hello view2.
</div>
</script>
<ul class="menu" ng-init="template='view1'">
<li><button ng-click="template='view1'">view1</button></li>
<li><button ng-click="template='view2'">view2</button></li>
</ul>
<div ng-include src="template"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With