Tuesday, August 6, 2019

javascript - Passing data in between controller without help of url?



I am creating two page webapp using AngularJS.
my Json file is:



{
"data": [

{ "name": "bhav",
"id": 123

},
{"name": "bhavi",
"id": 1234
},
{"name": "bhavk",
"id": 1235
}
]
}



my app.js(Routing file is):



myApp = angular.module('myApp', ['slickCarousel',
'ngRoute',
'myAppControllers',
'myAppServices','swipeLi'
]);

myApp.config(['$routeProvider',

function($routeProvider) {

$routeProvider.
when('/', {
templateUrl: 'partials/home-page.html',
controller: 'ProfileListCtrl',
}).
when('/profile/:typeofprofile', {
templateUrl: 'partials/profile-detail.html',
controller: 'ProfileDetailCtrl'

})
}]);


and my 1st page(home-page.html) is in given formate:







and on 2nd page(profile-details.html)
I want that id number of that profile considering I am using http.get request to pull data from Json file in controllers.



so please help me to fetch the id or name of clicked profile without passing through URL .



Note: I already look through ui-route link: Angular ui router passing data between states without URL but I didnt get that.


Answer



As you stated in the comments, you want to use $state.go() to pass your data.Using $state.go() to pass params is pretty simple as well. You need to inject ui.router in your application. I have created 2 partial views to show the passing of params where the params are passed from header.html to side.html.




Your JS will be something like below:



var app = angular.module('nested', ['ui.router']);
app.config(function($stateProvider,$locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider.state('top', {
url: "",
templateUrl: "header.html",
controller: 'topCtrl'
})

.state('top.side', {
url: '/app/:obj/:name',
templateUrl: "side.html",
controller: 'filterCtrl'
})
});

app.controller('topCtrl', function($scope,$state) {
$scope.goItem = function(){
$state.go('top.side',{obj:441,name:'alex'});

};
});


app.controller('filterCtrl', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});



Here is the working PLUNKER where you will find what you need to do regarding the views, controller and script:



http://plnkr.co/edit/M1QEYrmNcwTeFd6FtC4t?p=preview



I have provided the methods to pass $stateParams using both ui-sref and $state.go(). However, if you want to share the data among all the controllers. see my answer in this question:
Share Data in AngularJs


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...