I am new to Angular and I can't get my dropdown selectes to map to the browser URL (dynamic based on dropdown selections).
For example, the browser URL is "/home?color=Red&&size=Large". When I paste this URL in a new tab, I want the color and size dropdowns to already be selected as Red and Large. How do I do this?
My AngularJS controller code:
$scope.getResults = function() {
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
$scope.myColor = $location.search('color', $scope.myColor);
$scope.mySize = $location.search('size', $scope.mySize);
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
Check this Solution
ui-router in Angular:
$stateProvider.state('home', {
url: '/home/:color/:size',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
myApp.controller('MainCtrl', function($scope, $stateParams)
{
$scope.color=$stateParams.color;
$scope.size=$stateParams.size;
});
View
var params= { size:'24', color:red };
$state.go('home', params);
Related
I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);
addressbookController :
$http({
method: 'GET',
url: '/api/getnewgroup'
})
.then(function (response) {
$scope.draft.groups = response.data;
$scope.groups = response.data; // updated
}, function (response) {
console.log(response);
});
In this above controller, i am getting json response in $scope.draft.groups, I have this draft object in another controller called profsmsController.
profsmsController :
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
How to access $scope object ?
My Controller:
angular
.module('sampleApp.controllers', [])
//addressbook page controller
.controller('addressbookCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window, sharedService) {
// Groups
// get group
$http({
method: 'GET',
url: '/api/getnewgroup'
})
sharedService.getDraftPromise().then(function (response) {
$scope.groups = response.data;
$scope.draft.groups = response.data;
}, function (response) {
console.log('error');
});
})
.controller('profsmsCtrl', function ($http, $scope, $rootScope, $location,
$state, toastr, $timeout, $window) {
/* for drafts */
$scope.draft = {
draftType: '',
scheduledTime: '',
senderdata: '',
draftData: {
contacts: ''
},
groups: {
select: false
},
senderName: '',
message: '',
draftName: '',
createdOn: '',
updatedOn: ''
};
//add draft
$scope.addmanualInputDraft = function () {
$http.post('/api/addmanualinputdraft', $scope.draft).then(function (response) {
toastr.success("Added successfully!");
$('.bd-example-modal-lg-manual').modal('hide');
$state.reload();
});
}
})
My services.js:
angular
.module('sampleApp.services', [])
.factory('sharedService', function ($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function () {
return draftPromise;
}
};
});
my app.js:
'use strict';
angular
.module('sampleApp', ['sampleApp.controllers', 'sampleApp.directives','sampleApp.services','sampleApp.filters','ui.router','toastr','ngSanitize', 'ui.select'])
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/dash');
$stateProvider
.state('dash', {
url: '/dash',
templateUrl: 'partials/dash',
})
.state('quicksms', {
url: '/quicksms',
templateUrl: 'partials/quicksms',
controller: 'quicksmsCtrl'
})
.state('professionalsms', {
url: '/professionalsms',
templateUrl: 'partials/professionalsms',
controller: 'profsmsCtrl'
})
.state('file2sms', {
url: '/file2sms',
templateUrl: 'partials/file2sms',
controller: 'file2smsCtrl'
})
.state('addressbook', {
url: '/addressbook',
templateUrl: 'partials/addressbook',
controller: 'addressbookCtrl'
})
});
This is updated full code. I want to access $scope.draft.groups object from addressbook Controller.
In general, you'd want to create a service that holds your shared data:
myApp.factory('sharedService', function($http) {
var draftPromise = $http({
method: 'GET',
url: '/api/getnewgroup'
});
return {
getDraftPromise: function() {
return draftPromise;
}
};
});
In your controllers, you can then use the service by declaring it as a dependency:
myApp.controller("myController", function($scope, sharedService) {
sharedService.getDraftPromise().then(function(response) {
$scope.draft.groups = response.data;
});
});
Both controllers will refer to the same instance of draftPromise.
Note: if you are minifying your code, you'll want to use the alternate syntax for dependency injection that uses arrays. Take a look at the official documentation for dependency injection.
I really new with AngularJs and I'm trying to create multiple routes with different $http requests. My problem start when the route change and the page content show later.
I figure it out in some way and i think its not the right way.
Hope someone can tell me if there is a better way.
Note: AngularJs version: 1.6 | Using ui router
main.js
var asTwl = angular.module('asTwl', ['ui.router']);
asTwl.controller('generals', function($scope, $http, $timeout){
$scope.pageLoader = false;
$scope.getPageData = function(path, postData, obj){
$scope.pageLoader = true;
$http({
method: 'post',
url: path,
data: postData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then(function(response) {
if (response.data) {
$scope.data[obj] = JSON.parse(response.data);
$timeout(function(){
$scope.pageLoader = false;
}, 100)
}
})
.catch(function(e) {
new Error('Error: ', e);
throw e;
})
}
});
asTwl.controller('homePage', function($scope, $http){
var postData = {
//data...
}
$scope.getPageData('path', postData, 'home')
})
asTwl.controller('singlePage', function($scope, $http, $stateParams){
var postData = $stateParams;
$scope.getPageData('path', postData, 'page')
})
asTwl.controller('categoryPage', function($scope, $http, $stateParams){
var postData = $stateParams;
$scope.getPageData('path', postData, 'category')
})
asTwl.config(function($stateProvider, $urlRouterProvider, $locationProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl : 'templates/pages/home.html',
controller : 'homePage'
})
.state('info', {
url: '/info/:id',
templateUrl : 'templates/pages/info.html',
controller : 'singlePage'
})
.state('category', {
url: '/category/:type/:id',
templateUrl : 'templates/pages/category.html',
controller : 'categoryPage'
})
});
Thank you!
First, wrap your $http calls to services. Next,try to use resolve https://github.com/angular-ui/ui-router/wiki#resolve
Edit
Ok, example is here (without wrapping to service):
$stateProvider
.state('home', {
url: '/',
templateUrl : 'templates/pages/home.html',
controller : 'homePage',
resolve: {
routeData: function($http){
return $http({
method: 'post',
url: 'path',
data: postData /* your POST data - i don't know what is it for your code*/,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
}
}
})
.state('info', {
url: '/info/:id',
templateUrl : 'templates/pages/info.html',
controller : 'singlePage'
})
.state('category', {
url: '/category/:type/:id',
templateUrl : 'templates/pages/category.html',
controller : 'categoryPage'
})
And in controller:
asTwl.controller('homePage', function($scope, routeData){
$scope.someData = routeData;
})
You should first create a service which will be responsible for communicating with Server/API for playing around with data. You could include that method getPageData in that, it returns a promise object.
Service
app.service('myService', function($http){
var self = this;
self.getPageData = function(path, postData){
return $http.post(path,postData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' });
.catch(function(e) {
new Error('Error: ', e);
throw e;
});
});
Then you could easily utilize the resolve option of state of ui-router will wait till your ajax promise gets resolved.
.state('info', {
url: '/info/:id',
templateUrl : 'templates/pages/info.html',
controller : 'singlePage',
resolve: {
getData: function(myService) {
return myService.getPageData('path', {}, 'info')
}
}
})
In a nutshell your routes have to be changed like this:
.state('category', {
resolve: {
data : ($stateParams, dataService) => dataService.getData('path', $stateParams, 'category')
},
url: '/category/:type/:id',
templateUrl : 'templates/pages/category.html',
controller : 'categoryPage'
})
And getData method should be refactored to the service (dataService)
I new with angularjs and I'm trying use this generator-angular-fullstack,
I want the page login first and not the main, I play with the code and my solution is to add 'authenticate: true' in MainCtrl
angular.module('myapp')
.config(function ($stateProvider) {
$stateProvider
.state('main', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl',
authenticate: true
});
});
and comment the line 'event.preventDefault();' in app.js in the run function
.run(function ($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$stateChangeStart', function (event, next) {
Auth.isLoggedInAsync(function(loggedIn) {
if (next.authenticate && !loggedIn) {
//event.preventDefault();
$location.path('/login');
}
});
});
But I'm not sure is this changes are good or there are other best solutions.
to do this, your code will be like this
in main.js
angular.module('myapp')
.config(function ($stateProvider) {
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
});
});
in account.js
angular.module('myapp')
.config(function ($stateProvider) {
$stateProvider
.state('login', {
url: '/',
templateUrl: 'app/account/login/login.html',
controller: 'LoginCtrl'
})
.state('signup', {
url: '/signup',
templateUrl: 'app/account/signup/signup.html',
controller: 'SignupCtrl'
})
.state('settings', {
url: '/settings',
templateUrl: 'app/account/settings/settings.html',
controller: 'SettingsCtrl',
authenticate: true
});
});
in login.controller.js
angular.module('myapp')
.controller('LoginCtrl', function ($scope, Auth, $location, $window) {
$scope.user = {};
$scope.errors = {};
$scope.login = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.login({
email: $scope.user.email,
password: $scope.user.password
})
.then( function() {
// Logged in, redirect to home
$location.path('/main');
})
.catch( function(err) {
$scope.errors.other = err.message;
});
}
};
$scope.loginOauth = function(provider) {
$window.location.href = '/auth/' + provider;
};
});
For now I can execute my service in my AppCtrl but this is not right. Because the service is needed only when the user nagivated to page2. How can I execute my service when the page2 state is active? I tried resolve but couldn't get it work properly.
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('home');
$stateProvider.state('home', {
url: '/home',
templateUrl: 'home.html'
})
$stateProvider.state('page2', {
url: '/page2/:topicId',
templateUrl: 'page2.html'
// call my service here?
});
});
app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){
getTopicContent.request().success(function(data){
$scope.myList = data;
});
}]);
app.factory('getTopicContent', ['$http', function($http){
var query = function() {
return $http({
url: "http://www.corsproxy.com/mydata.me/level1/list.php",
method: "GET"
})
}
return {
request : function(){
return query();
}
}
}]);
You can create a controller for your page and inject service there.
$stateProvider.state('page2', {
url: '/page2/:topicId',
templateUrl: 'page2.html',
controller: 'Page2Ctrl'
});
Then your controller would look like
app.controller('Page2Ctrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){
getTopicContent.request().success(function(data){
$scope.myList = data;
});
}]);
if you want to try resolve, You can do something like this
$stateProvider.state('page2', {
url: '/page2/:topicId',
templateUrl: 'page2.html',
controller: 'Page2Ctrl',
resolve: {
content: getTopicContent.request().success(function(data){
return $scope.myList = data;
});
}
});
Then in your Page2Ctrl you can verify this content
app.controller('Page2Ctrl', ['$scope', 'getTopicContent', function($scope, content){
if (content) {
$scope.content = content;
}
}]);