Separate nav from ng-view - angularjs

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!

Related

$scope not updated - controller specification

I have the following routing:
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
when('/paneluser', {
templateUrl: 'views/panelUser.html',
controller: 'userCtrl'
}).
when('/paneluserblocks', {
templateUrl: 'views/userPanels.html',
controller: 'userCtrl'
}).
when('/registred', {
templateUrl: 'views/registredPanels.html'
}).
when('/color', {
templateUrl: 'views/color.html',
controller: 'alarmCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
When I specify a controller for a particular html template, my $scope variables are no longer updated in the view.
When I pull out the controller specification for a particular route, things return to normal.
The controller 'userCtrl' is accessed through $location and is intended for ordinary users. In turn, 'Ctrl panel' is the primary controller assigned to admin users.
Could anyone tell me what's going on?
I haven't all information, but it's working in my demo.
Config
var app = angular.module('app',['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/panel', {
templateUrl: 'views/panel.html'
}).
when('/make', {
templateUrl: 'views/makePanel.html',
controller: 'painelCtrl'
}).
otherwise('/', {
templateUrl: 'Index.html',
});
}]);
Definition of your controller:
app.controller('painelCtrl',painelCtrl);
painelCtrl.$inject = ['$scope'] //and more if you need $http, services, ...
function painelCtrl($scope){
$scope.hello= "hello world"
}
HTML
<h1>{{hello}}</h1>
I'm sorry for the igenuidade. I believed that the pages being in the same controller, I would never miss the reference:
When ('/panel', {
TemplateUrl: 'views/panel.html',
Controller: 'panelCtrl'
}).
When ('/make', {
TemplateUrl: 'views/makePanel.html',
Controller: 'panelCtrl'
}). cotinue...
In fact, views panel.html and makePanel.html will use the same controller structure, however we will have one instance for each view (variables will be reseted).
In my case I used factory functions to solve the problem. Every time I mute controller, I store the information of interest through a set () and get it through a get ();
app.factory("MonitorService", function () {
var info;
function set(data) {
info = data;
}
function get() {
return info;
}
return {
set: set,
get: get
}
});

Update to AngularJS 1.5.9 broke Angular Route

I have an Angular app that I had to update to 1.5.9 recently.
In my app it's necessary for someone to get an URL (eg.: http://somedomain/#/dashboard/1) and have a direct access to that screen, which is quite common.
In the latest version this worked perfectly, but now with 1.5.9 angular always redirects this request to the root path (http://somedomain/#/), causing all links to be broken.
How do I fix this? Is this some new rule, or a bug with this version, or some configuration I have to change?
--- UPDATE ---
My router code is a little confusing because I have several modules, and each one defines an object like this:
portal._routes = {
'/': {
controller: 'HomeController',
controllerUrl: 'portal/layout/controller/home',
templateUrl: 'app/portal/layout/template/home.html'
},
'/application': {
controller: 'HomeController',
controllerUrl: 'portal/layout/controller/home',
templateUrl: 'app/portal/layout/template/home.html'
},
'/dashboard': {
controller: 'DashboardListController',
controllerUrl: 'portal/dashboard/controller/dashboard-list',
templateUrl: 'app/portal/dashboard/template/dashboard-list.html'
},
'/dashboard/new': {
controller: 'DashboardFormController',
controllerUrl: 'portal/dashboard/controller/dashboard-form',
templateUrl: 'app/portal/dashboard/template/dashboard-form.html'
},
'/dashboard/:id': {
controller: 'DashboardViewController',
controllerUrl: 'portal/dashboard/controller/dashboard-view',
templateUrl: 'app/portal/dashboard/template/dashboard-view.html'
},
'/dashboard/public/:id': {
controller: 'PublicDashboardViewController',
controllerUrl: 'portal/dashboard/controller/dashboard-view-public',
templateUrl: 'app/portal/dashboard/template/dashboard-view-public.html'
},
'/dashboard/:id/edit': {
controller: 'DashboardFormController',
controllerUrl: 'portal/dashboard/controller/dashboard-form',
templateUrl: 'app/portal/dashboard/template/dashboard-form.html'
},
'/user/form': {
controller: 'UserFormController',
controllerUrl: 'portal/user/controller/user-form',
templateUrl: 'app/portal/user/template/user-form.html'
},
'/user/new': {
controller: 'UserFormController',
controllerUrl: 'portal/user/controller/user-form',
templateUrl: 'app/portal/user/template/user-form.html'
}
};
Then I have this in the main angular module file:
connecta.config(function ($controllerProvider, $compileProvider, $provide, $filterProvider, $translateProvider, $routeProvider, $httpProvider, $sceProvider, applications) {
configureLazyProviders($controllerProvider, $compileProvider, $provide, $filterProvider);
configureTranslations($translateProvider, window.navigator);
configureRoutes($routeProvider);
configureRequestInterceptors($httpProvider, applications);
configureHTTPWhitelist($compileProvider, $sceProvider);
configureAuthenticationListener($httpProvider, $routeProvider);
});
Which calls this configureRoutes function:
function configureRoutes($routeProvider) {
var allRoutes = buildRoutes(portal, presenter, maps);
angular.forEach(allRoutes, function (route, url) {
if (route.controllerUrl) {
if (!route.resolve) {
route.resolve = {};
}
if (!route.resolve.load) {
route.resolve.load = function ($q, $rootScope) {
var deferred = $q.defer();
require([route.controllerUrl], function () {
deferred.resolve();
$rootScope.$apply();
});
return deferred.promise;
};
}
}
$routeProvider.when(url, route);
});
$routeProvider.otherwise({
template: '<h1>Not Found</h1>'
});
}
Which calls this auxiliary buildRoutes function:
function buildRoutes() {
var finalRouteObject = {};
angular.forEach(arguments, function (module) {
// Coloca a referĂȘncia
angular.forEach(module._routes, function (value) {
value.module = module.name;
});
$.extend(true, finalRouteObject, module._routes);
});
return finalRouteObject;
}
This code was working and has not been changed recently, only Angular has been updated and it does this weird redirect to the root path.

Ionic Framework no refresh list when navigate

I am creating a mobile app in AngularJS. I call a resource that calls an API to give me values. Everything works fine, but with slow connections or 3G $ scope not cool me, and therefore when browsing the list of items is old.
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});
If you want to reload a part of your controller logic, every time the view is activated:
.controller('ExerciseController', function(
$q,
$scope,
$state,
Exercises,
$ionicView
) {
// reload exercises every time when we enter in the controller
$ionicView.enter(function(){
// This gets executed regardless of ionicCache
Exercises.query(function(data) {
$scope.exercises = data;
});;
});
});
Else, you can use the reload option on .state()

Refresh $scope and list of items slow connections

I am creating a mobile app in angularjs . I call a resource that calls an API to give me values. Everything works fine , but with slow connections or 3G $ scope not cool me and therefore when browsing the list of items is old
SERVICES.JS
.factory('Exercises', function($resource) {
// localhost: Local
// 79.148.230.240: server
return $resource('http://79.148.230.240:3000/wodapp/users/:idUser/exercises/:idExercise', {
idUser: '55357c898aa778b657adafb4',
idExercise: '#_id'
}, {
update: {
method: 'PUT'
}
});
});
CONTROLLERS
.controller('ExerciseController', function($q, $scope, $state, Exercises) {
// reload exercises every time when we enter in the controller
Exercises.query(function(data) {
$scope.exercises = data;
});
// refresh the list of exercises
$scope.doRefresh = function() {
// reload exercises
Exercises.query().$promise.then(function(data) {
$scope.exercises = data;
}, function(error) {
console.log('error');
});
// control refresh element
$scope.$broadcast('scroll.refreshComplete');
$scope.$apply();
}
// create a new execersie template
$scope.newExercise = function() {
$state.go('newExercise');
};
// delete a exercise
$scope.deleteExercise = function(i) {
// we access to the element using index param
var exerciseDelete = $scope.exercises[i];
// delete exercise calling Rest API and later remove to the scope
exerciseDelete.$delete(function() {
$scope.exercises.splice(i, 1);
});
};
})
APP.js
angular.module('wodapp', ['ionic', 'ngResource', 'wodapp.controllers','wodapp.services'])
// Run
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// ionic is loaded
});
})
// Config
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('slide', {
url: '/',
templateUrl: 'templates/slides.html',
controller: 'SlideController'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'templates/dashboard.html',
controller: 'DashboardController'
})
.state('exercise', {
url: '/exercise',
templateUrl: 'templates/exercises.html',
controller: 'ExerciseController'
})
.state('newExercise',{
url: '/newExercise',
templateUrl: 'templates/newExercise.html',
controller: 'NewExerciseController'
});
$urlRouterProvider.otherwise('/');
});

Dynamically switch ng-include between controllers

I have the following bit of code for my navigation that I want to update dynamically between pages.
<nav ng-include="menuPath"></nav>
Here is my app and routing set up
var rxApp = angular.module('ehrxApp', ['ngRoute']);
// configure our routes
rxApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainController',
templateUrl: '/content/views/index.html'
})
.when('/census', {
templateUrl: '/content/views/admission/census.html',
controller: 'censusController'
})
.when('/messages', {
templateUrl: '/content/views/account/messages.html',
controller: 'messagesController'
})
.when('/profile', {
templateUrl: '/content/views/account/profile.html',
controller: 'profileController'
})
});
In my main controller I set the menuPath value here:
rxApp.controller('mainController', function (userService, $scope, $http) {
evaluate_size();
$scope.menuPath = "/content/views/index.menu.html";
});
rxApp.controller('censusController', function ($scope, $http, $sce, censusService) {
$scope.menuPath = "/content/views/admission/census.menu.html";
evaluate_size();
});
When the page switches to the census view it should change the menu. What happens though is the first page loads the main menu, then no matter what other page you go to the menu never updates.
I imagine this problem has something to do with a primitive values and prototypical inheritance between child scopes, but would need to see more of your html to determine that. Without that, I propose an alternative way that may solve your problem and keep the config all in one place.
$routeProvider will accept variables and keep them on the route, even if angular doesn't use them. so we modify your routing by including the menuPath like so:
var rxApp = angular.module('ehrxApp', ['ngRoute']);
// configure our routes
rxApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainController',
templateUrl: '/content/views/index.html',
menuPath: '/content/views/index.menu.html'
})
.when('/census', {
templateUrl: '/content/views/admission/census.html',
controller: 'censusController',
menuPath: '/content/views/admission/census.menu.html'
})
.when('/messages', {
templateUrl: '/content/views/account/messages.html',
controller: 'messagesController'
})
.when('/profile', {
templateUrl: '/content/views/account/profile.html',
controller: 'profileController'
})
});
Remove setting $scope.menuPath from each controller, then finally add a watch on rootScope that will change the menuPath on $routeChangeSuccess
rxApp.run(['$rootScope', function ($rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current) {
if (current && current.$$route && current.$$route.menuPath) {
$rootScope.menuPath = current.$$route.menuPath;
} else {
$rootScope.menuPath = '';
}
});
}]);

Resources