Krisalay Krisalay - 3 months ago 13
AngularJS Question

changing the view of the div using angular ui-router

Here is the code which i have written so as to change my view (without any change in the url)

<a ui-sref="chat.menu" ng-click="click1();">Latest</a>
<a ui-sref="chat.menu" ng-click="click2();">Mail</a>
<div ui-view="{{item}}"></div>

var app = angular.module('myApp',['ui.router'])
.run(['$rootScope','$state','$stateParams', function($rootScope,$state,$stateParams){
$rootScope.$state = $state;
$state.$stateParams = $stateParams;
}]);


app.config(function($stateProvider,$urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home',{
url:'/',
templateUrl:'templates/main.html',
})
.state('chat',{
url:'/chat',
templateUrl:'templates/chatPage.html',
controller: 'chatController',
})
.state('chat.menu',{
views: {
'':{
template: '<h1>Blank</h1>',
},
'latest': {
template: '<h1>Latest</h1>',
},
'mail': {
template: '<h1>Mail</h1>',
}
}
});
});

app.controller('Controller', function($scope,$state, authentication){
$scope.item='';
$scope.click1 = function(){
$scope.item = "latest";

}
$scope.click2 = function(){
$scope.item = "mail";
}
});


Its working fine, but the problem is that I change the the view only once. Once a view is loaded in the ui-view, then another view is not getting loaded in it on the click of the button.

All i want is that, when the user click the button the view should be changed according to the click of the button without any change in the url.

Answer

So I'd trying something like this: having two states instead of one. If you want to keep only one state, you'd need to pass parameters to that state, but for a simple example like this, two states will work just fine:

myApp.config(function ($stateProvider){
    $stateProvider
    .state("latest", {
        url: "#",
        template: "<h1>Latest</h1>",
        controller: "Ctrl1"
      })
    .state("mail", {
        url: "#",
        template: "<h1>Mail</h1>",
        controller: "Ctrl2"
    });
});

What we are doing here is either setting the URL to the same in both states, or setting no URL at all. Also, if you want to assign controllers to your views, here is were we do it. You can assign no controllers, two different controllers, or the same controller if you would like.

Then setup your view like this:

<nav> 
    <a ui-sref="latest">Latest</a>
    <a ui-sref="mail">Mail</a>
</nav>

<div ui-view></div>

Here is a working JSFiddle