Dynamic routing depending on servers response in angularjs - javascript

So I am trying to configure my application in a way that lets it route dynamically depending on the servers response. My code is as follows.
HTML
<div ng-controller="CategoriesController" class="column">
<div layout-align="center center" ng-repeat="category in categories" >
<div class="category-button-text-english">{{category}}</div>
<md-button ng-click="submit()" class="category-button" aria-label="{{category}}">
<img ng-src="assets/images/categories/{{category}}.png"
alt="{{category}}">
</md-button>
<div class="category-button-text-translation">
{{category|uppercase| translate}}
</div>
Controller
$scope.submit=function(){
subCategoryService.getsubCategories().then(function (response)
{
console.log(response)
$rootScope.subcategories=response.data.data.subcategories;
$scope.category=response.data.data.category_name;
})
$location.path('/subcategory');
}
Service
.factory('subCategoryService', ['$http', '$httpParamSerializerJQLike', '$cookies','$rootScope', function ($http, $httpParamSerializerJQLike, $cookies,$rootScope,category){
var url2 = 'localhost:5000/api/subcategories/';
return {getsubCategories: function () {
return $http.get(url2);
}}}])
Another controller that gives the category names from server's response before the application comes on category page.
controller("userTypeController", function ($rootScope,$scope, $location, CategoryService) {
$scope.getCat=function(){
CategoryService.getCategories() .then(function (response)
{
$rootScope.categories=response.data.data.categories;
});
$location.path('/category');
};
So what I want is that after getting the category names from the server, it calls the right route depending on what button is clicked on the category page. For example depending on what button is clicked, the call should go like
localhost:5000/api/subcategories/CATEGORY_NAME. I get an array of categories when I go through the user type service and I want to use one of those category names to be passed in the subcategory service just as I wrote earlier. The flow of the application is like User->Category->Depending on category, show the subcategories. Any help would be appreciated. Thanks !!

Use like this
Route
.when("/category/:category_name", {
....
....
})
Service
.factory('subCategoryService', ['$http', '$httpParamSerializerJQLike', '$cookies','$rootScope', function ($http, $httpParamSerializerJQLike, $cookies,$rootScope,category){
var url2 = 'localhost:5000/api/subcategories/'+httpParamSerializerJQLike.category_name;
return {getsubCategories: function () {
return $http.get(url2);
}}}])

Related

How to retrieve and append data using the same web api get request in Angularjs

Here I am using "$http.get" request to retrieve data from Web API in Angular.js.
An API URL has a parameter call "pageNo=" and it's require to add a digit at the end of that parameter to retrieve a data of respective page number to maintain heavy request loads, each page has 10 list of records.
I took a scope variable ($scope.pageCount) and pass it with the URL, it's working fine and able to retrieve 10 list of records at once.
Now I am suppose to get the rest of data on scroll down (like using infinite-scroll) and append it with the existing list of data.
Is it possible or any way to retrieve more data from the same request?
I have added 'infinite-scroll' to the application and getting an alert on scroll down.
Following is the current working function.
app.controller('SpotLightCtrl', function ($scope, $http, shareEventID) {
$scope.pageCount = 1;
$http.get("https://stg.myapi.svc/pageNo="+$scope.pageCount+)
.then(function (response) {
$scope.data = response.data;
$scope.loadMore = function () {
alert('Load more records');
};
});
});
And the HTML code:
<div class="content-block spotlight-listing" ng-controller="SpotLightCtrl" infinite-scroll='loadMore()' infinite-scroll-distance='1'>
<h1>Spotlight</h1>
<div ng-repeat="event in data.eventList" class="deals-block">
<div class="col-md-4 col-xs-12 img-style">
<img ng-src="{{event.eventPosterImage}}" class="img-responsive img-rounded" />
</div>
</div>
</div>
Please share if any details is not clear, Any help would be appreciated...
You can put the http call in a function and call the function with the pagecount.
app.controller('SpotLightCtrl', function ($scope, $http, shareEventID) {
$scope.pageCount = 1;
$scope.data = [];
function getData() {
$http.get("https://stg.myapi.svc/pageNo=" + $scope.pageCount)
.then(function (response) {
$scope.data = $scope.data.concat(response.data);
});
}
$scope.loadMore = function () {
console.log('Loading more records');
++$scope.pageCount; //page count is incremented by 1, so
getData();
};
getData();
});
when the loadMore function is called pagecount is incremented by one and the next records are appended to the $scope.data

AngularJS $scope variable will not display in ionic view using GET request

I am having an issue displaying response data, returned from my factory,inside an ionic view page. I believe the issue has something to do with the way I am handling the promise, but I cannot pinpoint why. So to start the roadmap to my problem, here is my:
Factory
.factory('profileFactory', function ($http, $q) {
var config = {
headers: {
'MyKey': 'myvalue'
}
};
this.getEmployee = function (userId) {
return $http.get('http://someurlpathtogoto' + userId + 'etc', config).then(function (response) {
console.log(response.data)
return response.data;
})
}
return this;
})
The above code returns the JSON object I need for my controller so:
Controller
.controller('EmployeeCtrl', ['$scope', 'profileFactory', function ($scope, profileFactory) {
//Set back to false
$scope.profileLoaded = true;
$scope.serviceUnavailable = false;
$scope.setId = function (userId) {
profileFactory.getEmployee(userId).then(function(arrItems){
$scope.employee = arrItems;
$scope.firstName = $scope.employee.record[0].First_Name;
$scope.lastName = $scope.employee.record[0].Last_Name;
};
}])
Now when my page displays I want it to look like such:
Ionic View (Profile)
<ion-view view-title="Profile" ng-controller="EmployeeCtrl" hide-nav-bar="true">
<ion-pane>
<!-- TODO: BACK BUTTON, NO TITLE -->
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
<div ng-show="serviceUnavailable">
Directory service unavailable
</div>
<div ng-show="profileLoaded">
<br />
<center><img class="focus-img-circle" ng-src="default.png" /></center>
<center><b>{{firstName}} {{lastName}}</b></center>
</div>
</ion-content>
</ion-pane>
<ion-view>
All of this is invoked whenever a user presses on an arrow button in the app which should take them to their profile page to view some info. The following code appears in the previous view.
Ionic View (Search Results)
<ion-item class="item item-avatar item-button-right" ng-repeat="user in results" ng-controller="EmployeeCtrl">
<img ng-src="data:image/png;base64,{{user.pic}}">
<strong>{{user.first_name}} {{user.last_name}}</strong>
<div class="buttons" style="padding:20px;">
<button type="button" class="button button-icon ion-ios-telephone-outline customSearchIcon" ng-click=""></button>
<a class="button button-icon ion-ios-arrow-right customSearchIcon" ng-click="setId(user.id)" href="#/tab/search/profile"></a>
<button type="button" class="button button-icon ion-ios-heart-outline customSearchIcon" ng-click="addFavorite(user.id, user.first_name, user.last_name, user.pic)"></button>
</div>
</ion-item>
So essentially a user clicks on a persons tab, takes them to that profile where my factory is used to make a RESTful call to return a JSON object containing data about that user. Except nothing is being displayed in the Ionic View. If I hard code a userId in the controller and take away the function setId() it works but that obviously isn't an option. Does anyone see anything specifically that I am doing wrong? Been stuck on this for hours any help would be great.
I left a lot of code out to get my point across.
EDIT
The two views you see are different ionic templates. So using ng-controller="EmployeeCtrl is not happening twice in the same view.
The mistake is, on arrow click, you call the service and store the data to scope variable and then navigates to second view. The second view though uses the same controller as the first view, a new controller is being instantiated with empty scope - and hence your view is empty.
Instead of ng-click in <a> tag, modify your profile route to pass the userid as well - tab/search/profile/:userid and in anchor tag have ng-href= "#/tab/search/profile/{{user.id})" and in your profile controller get the userid from query string ($location.search().userid) and make the Ajax call.

Can't get the datas in angularJs

I have html page like
<div ng-controller="userListControl">
...
</div>
<div ng-controller="userDetailsControl">
....
</div>
And i have angular Js code is
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", ['$scope','$http', function($scope, $http)
{
$http.get('data/userData.json').success (function(data){
$scope.users = data;
$scope.users.doClick = function(user,event) {
userInfo(user);
}
});
}]);
function userInfo(users)
{
console.log(user);
userDirectory.controller("userDetailsControl", function($scope)
{
console.log('well')
$scope.user = users;
console.log($scope.user)
});
}
Here Everything is working fine. But when we are calling click event, That userInfo called with particular Data. But Second controller gives an error(angular js Error).
I am new one in angular jS. I dont know this logic is correct or not.
I have list items in first Controller. When we are clicking on list, It gets data from particular list and passed to another design. That design have detailed data. So the 2nd controller shows particular list detailed Section
First, There is no need to declare your controller inside a function - I don't think that you're trying to lazy-load controllers. Make it available to your app when it starts.
Second, you need to pass data to the userDetailsControl controller. There are various ways to do this, but here you could just use the $rootScope.
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", function($scope, $rootScope, $http)
{
$scope.selectUser = function(user){
$rootScope.selectedUser = user;
}
$http.get('data/userData.json')
.success (function(data){
$scope.users = data;
});
})
.controller("userDetailsControl", function($scope, $rootScope){
$rootScope.$watch("selectedUser", function(newVal){
$scope.user = newVal;
}
}
and in your HTML:
<div ng-controller="userListControl">
<button ng-repeat="user in users" ng-click="selectUser(user)">{{user.name}}</button>
</div>
<div ng-controller="userDetailsControl">
<div>{{user.name}}</div>
<div>{{user.otherDetails}}</div>
</div>

Angular JS | Passing data to 2 differents controllers on click

I've got some projects displayed in divs via ng-repeat.
Each div contains a link with the id of the project.
Basically I want to bind my project id on ng-click in order to update a factory. This will allow me to share the clicked project's id with another controller who will load the project details data only.
Here is my projects view:
<div ng-repeat="detail in projects.details">
<a ng-href="#!/project/project-details" ng-click="setId(detail.project_id)"><span></span></a>
</div>
Here is my factory:
app.factory('getGoodIdProjectDetails', function (){
var savedId = 1; //Default à 1
return {
getId : function () {
return savedId;
},
setId:function(idGet){
savedId = idGet;
return savedId;
}
}
});
Here are my controllers:
function ProjectCtrl($scope, $http, $timeout, getGoodIdProjectDetails) {
$scope.setId = function (idGet) {
$scope.idProjectDetails = getGoodIdProjectDetails.setId(idGet);
};
}
function ProjectDetailsCtrl($scope, $http, $timeout, getGoodIdProjectDetails) {
$scope.idProjectDetails = getGoodIdProjectDetails.getId();
}
In my view the console is displaying an error like I can't bind ng-click this way, but when I inspect the view it's sorting me the good thing, like ng-click="setId(8)"
I want the factory to update with the good id on click. Then I want to access this id in projectDetailsCtrl in order to load the project.
|| EDIT || : I changed the ng-click, that works fine, everything's good. Thx all
try this:
<div ng-repeat="detail in projects.details">
<a ng-href="#!/project/project-details" ng-click="setId(detail.project_id)"><span>Voir le projet ></span></a>
</div>
you don't need to use binding expression {{}} to pass values to functions

AngularJS reloaded controller dont change DOM

I have an angularJs Application.
In there i have a "LayoutCtrl" (LayoutController) which is saying (for example) "How many head menu links are existing".
I have created my Controller and my Service - it works fine.
Now, in some cases the site needs new HeadMenu-Links (e.g. at login / logout) or widgets (little boxes with extra content at side).
So i getted the $scope from the LayoutCtrl to the controller (for grabbing it later and chaning its values).
At testing (alert some values) my $scope has always the corrent values, also changes in the returned JSON (from php service).
But the DOM dont changes.
What could it be?
The part of Layout:
<div ng-controller="LayoutCtrl">
<div desc='header' class='header' >
<a desc='hp_link' class='hp_link' href="#{{header.index}}">
<img desc='banner' class='banner' ng-src="{{header.banner}}" src="zkLib/f/img/ajax-loader-sm.gif">
</a>
<div desc='headerRow' class='headerRow'>
<div desc='headerMenu' class='headerMenu'>
<span ng-repeat="m in header.mHead">
<span desc='hmLink' class='hmLink' >
<a desc='headerLink' class='headerLink' href="{{m.link}}">{{m.text}}
<img desc='headerImg' class='headerImg' ng-src="ico/{{m.image}}" heightt="16px;"/>
</a>
</span>
</span>
</div>
<div desc='networksMenu' class='networksMenu'>
<span ng-repeat="n in header.network">
<span desc='nwLink' class='nwLink' >
<a desc='networkLinK' class='networkLinK' target="_blank" title="{{n.name}}" href="{{n.link}}">
<img desc='networkImg' class='networkImg' ng-src="zkLib/f/img/icons/{{n.icon}}"/>
</a>
</span>
</span>
</div>
</div>
</div>
</div>
The Controller:
app.controller("LayoutCtrl", ["$scope", "$route",
"HeaderService", "AppService", "WidgetsService", "FooterService",
function($scope, $route, HeaderService, AppService, WidgetsService, FooterService) {
$scope.refresh = function(route) {
HeaderService.query().then(
function(result) { $scope.header = result.data }, function(result) {}
);
WidgetsService.query().then(
function(result) { $scope.widgets = result.data }, function(result) {}
)
$scope.$route = route;
alert(JSON.stringify($scope.header));
};
$scope.refresh($route);
AppService.query().then(
function(result) { $scope.app = result.data }, function(result) {}
);
FooterService.query().then(
function(result) { $scope.footer = result.data }, function(result) {}
);
AppService.$scope = $scope;
}]);
One of the called services:
app.factory('HeaderService', ['$http', '$q',
function ($http, $q) {
var service = {};
service.query = function() {
var data = $http.get(sAddr('header'));
var deffered = $q.defer();
deffered.resolve(data);
return deffered.promise;
};
return service;
}]);
(sAddr returns the corrent server path to service)
On other Controllers (e.g. index page, user page...) i call
AppService.$scope.refresh($route);
to force the controller refresh (new Menus? New Widgets?) and it reload correctly (i think) - the alert in the code above print me out the correct json.
But the DOM dont change.
What i´m doing wrong?
I´ve builded this pattern with this example code from an other StackOverFlow-Question:
enter link description here
I´ve build an similar example with the Servoce.$scope.refresh-Call on other Controller (TestController) - it worked fine... but here - with no differences, not.
Thanks for answers - Kai
You try $scope.$apply() or $rootScope.$digest() to get all of the data refreshed in your DOM. Updating any of the models from outside of the controller it is bound to will update the data but Angular doesn't know about it. Sometimes, setting a watch with $scope.$watch and updating the values inside the controller will give you the refreshed data in the DOM.
Trying a $scope.$digest() at the end of your promises is also an option.
http://nathanleclaire.com/blog/2014/01/31/banging-your-head-against-an-angularjs-issue-try-this/

Categories

Resources