I'm new to Angular and I'm trying to create a Single Page application with 2 views.
When I load the app is always shows me the first one of the 2 views regardless of what route I type in the browser.
This is the javascript code:
var appControllers = angular.module('appControllers', []);
appControllers.controller('HomeController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
appControllers.controller('InformationController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
var app = angular.module('myApp', ['ngRoute', 'appControllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/productlist.html',
controller: 'HomeController'
}).
when('/info', {
templateUrl: 'partials/information.html',
controller: 'InformationController'
})
}]);
app.controller('HomeController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
app.controller('InformationController', function($scope, $http) {
var promise = $http({
method: 'GET',
url: 'restaurant.json'
});
promise.then(function(obj) {
$scope.data = obj.data;
});
});
I tried to change the order in which I define the 2 routes for the 2 view templates.
If I define the info template first the that template will be shown always and the other one will not be shown.
Can someone help me fix this problem?
Here is a fully functioning ngRoute:
sampleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/a', {
templateUrl: 'templates/a.html',
controller: 'a'
}).
when('/av2', {
templateUrl: 'templates/av2.html',
controller: 'av2',
}).
when('/a3', {
templateUrl: 'templates/a3.html',
controller: 'a3'
}).
otherwise({
redirectTo: '/a'
});
}]);
Try cross comparing that with your code and see if you find any differences. I think it may have to do with how you initiate your app very late into the script:
var app = angular.module('myApp', ['ngRoute', 'appControllers']);
Typically, bootstrapping your app is one of the most important things to do and should be at the top as a result.
Related
I have an angular app that needs to do a quick http request to get some config information before the rest of the application is initiated, at least before the controllers. Looked into using $UrlRouterProvider, but I did not figure out how to make the app wait for the http be done.
What I need to be finished:
$http({method: 'GET', url: '/config'}).then(function(res) {
configProvider.setConfig(res.data.config);
}
You can create a separate js file where you can make http request and then initialize/bootstrap your app via js code instead of ng-app in html code.
Refer the below code:
(function() {
var application, bootstrapApplication, fetchData;
application = angular.module('app');
fetchData = function() {
var $http, initInjector;
initInjector = angular.injector(['ng']);
$http = initInjector.get('$http');
$http.get('<url>');
};
bootstrapApplication = function() {
angular.element(document).ready(function() {
angular.bootstrap(document, ['app']);
});
};
fetchData().then(bootstrapApplication);
})();
I hope it helps.
Resolve must be declared on state, not on the view
change
.state('app', {
abstract: true,
url:'/',
views: {
"content": {
templateUrl: "myurl.html"
},
resolve {
myVar: ['$http', 'myService', function($http, myService) {
return $http({method: 'GET', url:'url'})
.then(function(res) { //do stuff })
to
.state('app', {
abstract: true,
url:'/',
views: {
"content": {
templateUrl: "myurl.html"
}
},
resolve {
myVar: ['$http', 'myService', function($http, myService) {
return $http({method: 'GET', url:'url'})
.then(function(res) { //do stuff })...
I want to run a service that read total unread message when user visits a few particular page. I'm using resolve for this. I set up a factory which communicates with the backend through a http call and the backend returns the count of total messages and I wanna show this in html page but all I am getting is error.
( function () {
var countAllUnreads = function($location, $q, AuthService3)
{
var deferred = $q.defer();
AuthService3.fetchUnreadNotifications().then(function (res)
{
console.log('this is me');
$scope.numOfNotifications =res.data.totalUnread;
});
}
angular.module('myApp', [
'ngRoute',
'myApp.login',
'myApp.home',
'myApp.directory',
'myApp.forgotpassword',
'myApp.myProfile',
])
.factory('AuthService3', ["$http", "$location", function($http, $location){
var baseUrl = 'api/';
var fetchUnreadNotifications = function()
{
return $http.post(baseUrl + 'getAllUnreadNotifications');
}
return {fetchUnreadNotifications: fetchUnreadNotifications} ;
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'app/components/login/loginView.html',
controllerAs: 'vm'
})
.when('/forgotpassword', {
controller: 'ForgotpasswordController',
templateUrl: 'app/components/forgotpassword/forgotpasswordView.html',
controllerAs: 'vm'
})
.when('/directory/:directoryType', {
controller: 'DirectoryController',
templateUrl: 'app/components/directory/directoryView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.when('/home', {
controller: 'HomeController',
templateUrl: 'app/components/home/homeView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.when('/myprofile', {
controller: 'MyProfileController',
templateUrl: 'app/components/profile/myProfileView.html',
resolve: {notifications:countAllUnreadsn,},
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/login'
});
}]);
})();
The problem is that you are using $scope within the function which loads notifications. $scope will not be available there since it might not be created yet. You need to return a promise and the resolved value can be injected as a dependency to the controller.
var countAllUnreads = function($location, $q, AuthService3)
{
var deferred = $q.defer();
AuthService3.fetchUnreadNotifications().then(function (res)
{
deferred.resolve(res.data.totalUnread);
});
return deferred.promise;
};
And in your controllers, have a dependency for 'notifications'.
Ex: function HomeController($scope, $http, notifications){ }
I'm brand new to Angularjs and am trying to set up a new site but I'm confused as to the set up. I have a module and am using $route to successfully navigate but I'm lost as to what to do with my nav. When I load the module I want to read my database for a list of links that the user is allowed to access then spit them out in the nav. I don't want to repeat this in every view because I don't need to. So I'm trying to figure out how to run the ajax call once and then keep changing the view (I'd also like to add a class .selected to whatever view they're on). How would I go about doing that, with a directive?
(function () {
var app = angular.module('manage', ['ngRoute', 'manageControllers']);
/*
I've tried this but obviously $http isn't injected. Can I even do that?
var thisApp = this;
$http.get('/test/angular/php/angular.php', {params: {'function': 'nav'}}).then(function successCallback(response) {
});
*/
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
}).
when('/inventory/', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
when('/inventory/:mvKey', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
when('/inventory/:mvKey/:tab', {
templateUrl: 'templates/inventory.html',
controller: 'InventoryCtrl'
}).
/* etc...*/
}
]);
})();
EDIT:
My attempt at getting the nav to run once
controllers.js
var manageControllers = angular.module('manageControllers', []);
var thisApp = this;
nav = null;
navSelected = '/';
manageControllers.controller('NavCtrl', ['$scope', '$http', function($scope, $http) {
if (thisApp.nav === null) {
$http.get('php/angular.php', {params: {'function': 'nav'}}).then(function successCallback(response) {
console.log(response.data);
thisApp.nav = response.data;
$scope.nav = thisApp.nav;
$scope.select = thisApp.navSelected;
});
} else {
$scope.nav = thisApp.nav;
$scope.select = thisApp.navSelected;
}
}]);
manageControllers.controller('DashCtrl', ['$scope', function($scope) {
thisApp.navSelected = '/';
}]);
I would swith to UI Router (https://github.com/angular-ui/ui-router) instead of $route. It allows you being much more flexible with your routing.
A Small example:
app.config(['$stateProvider',
function($stateProvider) {
$stateProvider.
state('/', {
url: '/',
views: {
'': {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
},
'nav#': {
templateUrl: 'path/to/nav.html',
controller: 'NavCtrl'
},
}
}).
state('/inventory/', {
url: '/',
views: {
'': {
templateUrl: 'templates/dash.html',
controller: 'DashCtrl'
},
'nav#': {
templateUrl: 'path/to/nav.html',
controller: 'NavCtrl'
},
}
}).
// ...
and in your index.html
<div ui-view="nav"></div>
<div ui-view ></div>
Take a closer look at UI Router's doc, there's much more you can do with it!
I'm making a signup form using satellizer.
But it does not go to the right url
My console displays the following:
POST http://localhost:8000/http://104.236.150.55/auth/register 404 (Not Found)
view2.js:185 Not found
This is my config.js:
.config(['$routeProvider', '$locationProvider', '$authProvider', function($routeProvider, $locationProvider, $authProvider) {
$routeProvider
//for Landing page
.when('/view2', {
templateUrl: 'view2/view2.html',
controller: 'View2Ctrl'
})
.when('/activity', {
templateUrl: 'view2/activity.html',
controller: 'ActivityCtrl'
})
.when('/signup', {
templateUrl: 'view2/signup.html',
controller: 'UserCtrl'
});
$authProvider.signupUrl = "http://example.com/auth/register";
}])
and my controller:
.controller('UserCtrl', ['$scope', '$auth', function($scope, $auth) {
$scope.signup = function() {
var user = {
email: $scope.email,
password: $scope.password
};
$auth.signup(user)
.catch(function(response) {
console.log(response.data);
});
}
}]);
How do i access them with absolute urls?
Set in your config:
$authProvider.baseUrl = null;
i am just learning basics of angular and today it started to change my app using a factory to get data and implementing route provider ! So far everything works fine! But when I try to add data on another view and head back to my list view scope is reloaded again from factory and no added data shows up.
My approach won't work because each time change my view I will call my controller which reloads data from factory! What can I do to make my Add template will work and changes data everywhere else too.
Maybe somebody can give me a tip how to cope with this problem ?
script.js
var app = angular.module('printTrips', ['ngRoute']);
app.factory('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
app.controller('TripController', function($scope, $filter, tripFactory) {
$scope.trips = [];
tripFactory.getTrips().success(function(data){
$scope.trips=data;
var orderBy = $filter('orderBy');
$scope.order = function(predicate, reverse) {
$scope.trips = orderBy($scope.trips, predicate, reverse)};
$scope.addTrip = function(){
$scope.trips.push({'Startdate':$scope.newdate, DAYS: [{"DATE":$scope.newdate,"IATA":$scope.newiata,"DUTY":$scope.newduty}]})
$scope.order('Startdate',false)
$scope.newdate = ''
$scope.newiata = ''
$scope.newduty = ''
}
$scope.deleteTrip = function(index){
$scope.trips.splice(index, 1);
}
});
});
view.js
app.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view1',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'TripController',
templateUrl: 'view2.html'
})
.when('/addtrip',
{
controller: 'TripController',
templateUrl: 'add_trip.html'
})
.otherwise({ redirectTo: 'View1.html'});
});
Here is my plunker
Thanks for your help
You should use Service instead of Factory.
Services are loaded each time they are called. Factory are just loaded once.
app.service('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});