I have started with angular but I have some problem with kind of object in angular.
What kind of $scope in this screen? and how to get 'title' in that.
Here is my code.
define(['angularAMD', 'angular-route'], function(angularAMD) {
var app = angular.module("coreModule", ['ngRoute']);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when("/home", angularAMD.route({
templateUrl: 'home.html',
controller: 'HomeCtrl',
title: 'Home',
controllerUrl: 'ctrl/home',
})).
when("/list", angularAMD.route({
templateUrl: 'views/news.html',
controller: 'newsCtrl',
controllerUrl: 'ctrl/news'
})).
otherwise({
redirectTo: '/home'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: true,
});
}
]);
app.run(['$rootScope', '$route',
function($rootScope, $route) {
$rootScope.$on('$routeChangeSuccess', function() {
console.log($rootScope);
});
}
]);
app.factory('Page', function() {
var title = 'default';
return {
title: function() {
return title;
},
setTitle: function(newTitle) {
title = newTitle;
console.log(title);
}
};
});
return angularAMD.bootstrap(app);
});
I want to get 'title' from controller.
Any idea? Thanks
I am still not sure what you are trying to do but here is my guess.
If you are trying to set the page title from the controller then here is how I would do it. And that is Not set it from the controller. I would set it on the state as you have already done and then pick it up on every state change.
aspStratMed.run(['$rootScope', function ($rootScope)
{
$rootScope.$on('$stateChangeStart', function (event, toState)
{
if (toState.data && toState.data.pageTitle)
$rootScope.pageTitle = toState.data.title;
});
And then in the HTML just use this where every you need the page title
{{pageTitle}}
Related
I can't wrap my head around this, I'm really struggling with ui-routeand $stateChangeSuccess and $watch, got two issues. I'm trying to change a value of a parameter, when I change the state, click a url. I think it's important to know that I use sub-states. With my current setup I get that the $stateChangeSuccess triggers twice on load, meaning it sets the value right away. What I'm trying to do is to only have it set on change of url.
My route looks like this, I'm trying to set the value of a parameter
.state('medications', {
url: '/medications',
templateUrl: '/partials/home.html',
controller: 'mainController',
params: { showSection: false },
resolve: {
postPromise: ['medicationservice', function(medicationservice) {
return medicationservice.getAll();
}]
}
})
.state('medications.add', {
url: '/add',
templateUrl: '/partials/home.html',
controller: 'mainController',
params: { showSection: true },
})
in my controller I got the following, where I set the openSesame parameter to false explicitly on init, but as described it triggers and sets it to true.
mainModule.controller('mainController', [
'$scope',
'$state',
'$rootScope',
'medicationservice',
function($scope, $state, $rootScope, medicationservice) {
$scope.medication = {};
$scope.medications = medicationservice.posts;
$scope.openSesame = false;
$rootScope.$on("$stateChangeSuccess", function() {
$scope.openSesame = true;
console.log($scope.openSesame);
});
}]);
in my plunker the state change works once, that is if I use the $rootScope.
You can actually use $stateChangeSuccess without $injecting $rootScope. You can set a listener on the $scope object instead. Take a look at the following plunker.
And the revised code:
(function() {
var app = angular.module('myApp', ['ui.router']);
app.controller('mainController', [
'$scope',
'$state',
function($scope, $state) {
$scope.medication = {};
$scope.openSesame = false;
$scope.$on('$stateChangeSuccess',function(event, toState){
$scope.openSesame = toState.params.showSection;
});
$scope.triggerMe = function() {
alert('yes');
};
}
]);
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('medications', {
url: '/medications',
template: '<div>{{openSesame}}</div>',
controller: 'mainController',
params: {
showSection: false
}
})
.state('medications.add', {
url: '/add',
template: '<div>{{openSesame}}</div>',
controller: 'mainController',
params: {
showSection: true
},
});
$urlRouterProvider.otherwise('medications');
}
]);
}());
Click your buttons medication and medication add to see the value change.
The callback of $stateChangeSuccess, you have access toState, fromState. Or check current state name
$rootScope.$on("$stateChangeSuccess", function() {
if ($state.current.name == "medications.add") {
$scope.openSesame = true;
}
console.log($scope.openSesame);
});
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 getting the classic "Module 'ngLocale' error is not available" error when angular tries to load up my module. I can't for the life of me figure out what dependency I am missing. Here's my app.js:
(function() {
var app, dependencies;
dependencies = ["ngRoute"];
app = angular.module('myapp', dependencies);
app.run(['$location', '$rootScope'], function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
$rootScope.title = current.$$route.title;
});
});
app.config(['$routeProvider'], function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'Content/views/home.html',
controller: 'homeController',
title: 'Home'
}).otherwise({
redirectTo: '/'
});
});
}).call(this);
My javascript files are loaded correctly in order. What am I missing?
you have to include the function in the array:
app.run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);
and:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'Content/views/home.html',
controller: 'homeController',
title: 'Home'
}).otherwise({
redirectTo: '/'
});
}]);
I am looking at building a clientside authentication for my angular app. The routing looks like this:
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/customers', {
controller: 'CustomersController',
templateUrl: 'customers.html',
secure: true
})
.when('/login/:redirect*?', {
controller: 'LoginController',
templateUrl: 'login.html'
})
.when('/testing', {
controller: 'TestController',
templateUrl: 'testing.html' })
.otherwise({ redirectTo: '/customers' });
}]);
When I click on the login link it wont let me go to the login page?
See also this plunkr: http://plnkr.co/edit/TVSnCp8AtBKVfcYdWvN2?p=preview
Please update the app.js
(function () {
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/customers', {
controller: 'CustomersController',
templateUrl: 'customers.html',
secure: false
})
.when('/login', {
controller: 'LoginController',
templateUrl: 'login.html'
})
.when('/testing', {
controller: 'TestController',
templateUrl: 'testing.html' })
.otherwise({ redirectTo: '/customers' });
}]);
app.run([ '$rootScope', '$location', 'authService',
function ( $rootScope, $location, authService) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (next && next.$$route && next.$$route.secure) {
if (!authService.user.isAuthenticated) {
authService.redirectToLogin();
}
}
});
}]);
}());
var testApp = angular.module('testApp', ['firebase'])
.config(['$routeProvider','$locationProvider',function
($routeProvider,$locationProvider)
{
$routeProvider
.when('/', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
})
.when('/test', {
templateUrl: '/views/test.html',
controller: testCrtl,
resolve:
{
firedata: function($q,angularFire){
var deffered = $q.defer();
var ref = new Firebase('https://shadowfax.firebaseio.com/items');
ref.on('value', function(result){
deffered.resolve(result.val());
});
return deffered.promise;
}
}
})
.otherwise({
redirectTo: '/'
});
// $locationProvider.html5Mode( true );
}]);
angular.module('testApp')
.controller('MainCtrl', ['$scope','$routeParams','$rootScope', function ($scope,$routeParams,$rootScope) {
$scope.load = function(){ return false;}
$rootScope.$on('$routeChangeStart', function(next, current) {
$scope.load = function(){ return true;}
});
}]);
testApp.controller('TestCtrl',['$scope','$timeout','Fire','firedata','testCrtl']);
var testCrtl = function ($scope,$timeout,Fire,firedata) {
$scope.items=firedata;
};
In the code above, why is the value of $scope.items=firedata; null? Please explain how can I perform a Google-like route change to preload data for the controller? This example works like John Lindquist explains, but when I use Firebase's native JS library, I can't get the data preloaded.
Also, using the Firebase angularFire library doesn't help, because it uses $scope as a parameter and it's not possible to pass $scope to the resolve function.
You should be able to use angularFireCollection to preload data:
.when('/test', {
templateUrl: '/views/test.html',
controller: testCrtl,
resolve: {
firedata: function(angularFireCollection){
return angularFireCollection('https://shadowfax.firebaseio.com/items');
}
}
})