AngularJS $templateCache under MVC - angularjs

I couldn't find any documentation or article on this.
We here at the company I work for have MVC project.
And we build Angular SPA on top of it.
Also we want it to work offline.
So, I need cache. Found $templateCache module in AngularJS.
And trying to implement it.
Since the project is MVC, all the templates I want to load into ng-view are actually MVC partial views and I can load them by calling {Controller}/{Action}.
But the are no examples on internet ho to implement $templateCache in this case.
All the examples show how to use static templates, like mytemplate.html or just strings. This won't work under MVC.
So, I was trying to figure out how to accomplish that, wrote this, for app.ts:
namespace AppDomain {
"use strict";
export let app = angular.module("app", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", { templateUrl: "Home/Template?name=Main", controller: "Controller", controllerAs: "vm" })
.when("/About", { templateUrl: "Home/Template?name=About", controller: "Controller", controllerAs: "vm" })
.when("/Contact", { templateUrl: "Home/Template?name=Contact", controller: "Controller", controllerAs: "vm" })
.otherwise({ redirectTo: "/" });
});
app.run(function ($templateCache) {
$templateCache.put("Home/Template?name=Main", "Home/Template?name=Main");
$templateCache.put("Home/Template?name=About", "Home/Template?name=About");
$templateCache.put("Home/Template?name=Contact", "Home/Template?name=Contact");
});
}
Obviously this doesnt work. Any suggestions? Thanks.

Related

AngularJS SPA Refresh page

While developing some SPA AngularJS Application I define the rooting with $routeProvider. Everythings works fine, but I get tired with clicking through the whole application to see particular changes I've done anytime I republish the application to the server. Is there a possibility to change this behaviour? I mean, when I hit refresh on my browser or use some tools for automatical refreshing (like LiveReload Server) is there a way to tell angularJS to not to navigate to the default page?
Regarding to the comments below, here is the routing content.
Below is the MainRoutingContent
'use strict'
angular.module('MainModule')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'webapp/modules/authentication/views/login.html',
hideMenus: true
})
.when('/register', {
controller: 'RegistrationController',
templateUrl: 'webapp/modules/registration/views/register.html'
})
.when('/', {
controller: 'HomeController',
templateUrl: 'webapp/modules/home/views/home.html'
})
.otherwise({ redirectTo: '/login' });
}]);
The single html page has the ng-view defined:
<div>
<div ng-view></div>
</div>
And some additional for the RegistrationModule:
angular.module('RegistrationModule')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/register/user', {
controller: 'UserRegistrationController',
templateUrl: 'webapp/modules/registration/views/register-user.html'
})
.when('/register/company', {
controller: 'CompanyRegistrationController',
templateUrl: 'webapp/modules/registration/views/register-company.html'
});
}]);
Ok, I got it. I defined some run block in the main module of my application with the redirection to the /login page. Here is the code:
angular.module("app", [...])
.run(['$location',
function ($location) {
$location.path('/login');
}])
If someone will get such an issue with refreshing the page in the future, please look for some run block defined in your code.

Experience with making 2 base templates for site

I understand how to make a basic single page app with ng-view, and routing the templates into the index.html. However, I want to separate the website into the Home section (views: Home, About, Registration, Login), then when the user logs in they go to a dashboard which has its own set of views. The Dashboard (/dashboard/user:id) and Home Section (/, /about, etc.) would have separate base templates.
Would this just be two separate apps altogether with different base templates? Anyone have experience setting something like that up?
If you are talking about only changing the views you can use the $routeProvider to define your templates, controllers, etc. Have a look at ui-route "Nested States & Views" at https://github.com/angular-ui/ui-router
$routeProvider
.when('/', {
templateUrl: 'template/home/home.tpl.html',
controller: 'LomeCtrl',
controllerAs: 'vm'
})
.when('/dashboard/user:id',{
templateUrl: 'template/dashboard/dashboard.tpl.html',
controller: 'dashboard',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
Another approach you can take it to create a provider to display the template based on user login status.
angular.module('myApp', ['ngRoute', 'loginService'])
.config(['$routeProvider', 'loginCheckerProvider', function($routeProvider, loginCheckerProvider) {
$routeProvider.
when('/', {
templateUrl: (loginCheckerProvider.isLoged()) ? 'loggedin.html' : 'loggedout.html'
//controller: 'aboutCtl',
})
.otherwise({
redirectTo: '/'
});
}]);
And the provider:
(function () {
'use strict';
function loginChecker() {
this.$get = angular.noop;
//Do your logics to check if user is loggedin and add the result to the return below
//toggle the return below between true and false
this.isLoged = function(){
return true;
}
}
angular.module('loginService',[])
.provider('loginChecker', loginChecker);
})();
I created a plunker to test and it is working. To test it go to loginservice.js file and toggle the return to true/false, you will see the template updating.

Controllers and how they should be implemented in Angular?

Sorry if this seems like a stupid or simple question but I am a little confused, I have been looking up many different kinds of tutorials for Angular to understand the concept and how to create an application.
The issue is how to you attach a Controller to the Page, I have seen two methods:
Add the controller script to the page
Display Controller inside the app.js where the Website Routing is.
Here is what I have at the moment please let me know if there is any issues in this code:
var app = angular.module('myApp', [
'ngRoute'
]);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'homeController'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: ''
}).
when('/signup', {
templateUrl: 'partials/signup.html',
controller: ''
}).
when('/dashboard', {
templateUrl: 'partials/dashboard.html',
controller: ''
}).
otherwise({
redirectTo: '/404',
templateUrl: 'partials/404.html'
});
}]);
app.controller('homeController', ['$scope', function($scope) {
$scope.message = "This is the Home Page";
}]);
Again I am really new to Angular.
Updated to single Controller file:
app.js:
var app = angular.module('myApp', [
'ngRoute'
]);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'controllers/homeController.js'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: ''
}).
when('/signup', {
templateUrl: 'partials/signup.html',
controller: ''
}).
when('/dashboard', {
templateUrl: 'partials/dashboard.html',
controller: ''
}).
otherwise({
redirectTo: '/404',
templateUrl: 'partials/404.html'
});
}]);
controller file:
app.controller('homeController', ['$scope', function($scope) {
$scope.message = "This is the Home Page";
}]);
Nope, your code is fine. I generally use two different files app.js for all the routing options and a controller.js file for the different controllers. A single file seems a bit too cluttered to me.
A single file per controller works but I see for most usercases it turns out just a few lines of code per page for me, but you can if you have extensive codes in each controller
I create a Controller for every model in my database: e.g: ProjectController.js, PeopleController.js, etc. And I use app.js just for routing and general controllers like header, footer, etc.
There isn't a strict way to do it, you have to decide it based on your architecture design. But i can give you a tip: Never define your controllers in your .html file because it makes it awful and less readable.
That's a purely organizational choice. As long as the browser has the code of the controller available, it doesn't matter.
But unless you're creating a tiny demo, having all the controllers defined in a single JavaScript file will quickly become unmanageable: the file will be too large, you'll search for the controllers constantly, and everyone in the team will modify the same file, leading to conflicts, etc.
The simple rule is: one JS file per AngularJS component.
If you're concerned about two many JS files having to be loaded by the HTML page in production, then make sure to learn using gulp or grunt, and to generate a single minified JS file from all the small JS files used during development.
EDIT:
the controller attribute of the route is not supposed to be the path of a JS file. It's supposed to be the name of a controller. It should thus stay exactly as it was in the first, working example.
You need to understand how the browser works: if the HTML contains two <script> elements, it works the same way as if it had a single one with the code of the two scripts concatenated. So splitting the code in two files doesn't change the way the code is written.
Change your route specification to the following code:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'homeController' //change here
//controller should be the name of the controller,
//not the file containing the controller function
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: ''
}).
when('/signup', {
templateUrl: 'partials/signup.html',
controller: ''
}).
when('/dashboard', {
templateUrl: 'partials/dashboard.html',
controller: ''
}).
otherwise({
redirectTo: '/404',
templateUrl: 'partials/404.html'
});
}]);

AngularJS - Dynamic URLs for new page

I am AngularJS beginner so sorry for this silly question. I am working on a page called menu.html which has severals links of food categories such as Noodle, Soup, Sandwiches. When user click on any of those links it will lead to a page that list the food that are relevant to the category and with different URL. For example, click on "Noodle", the url of the new page will be menu/Noodle.html. Would you please tell me how to do it with AngularJS? Thank you so much.
First of all you need to include angular-route.js file for angular.
Refer this. https://docs.angularjs.org/misc/downloading
angular.module('myapp',[]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { templateUrl: '/menu/Noodle.html', controller: HomeController });
$routeProvider.when('/about', { templateUrl: '/pages/about.html', controller: AboutController });
$routeProvider.when('/privacy', { templateUrl: '/pages/privacy.html', controller: AboutController });
$routeProvider.when('/terms', { templateUrl: '/pages/terms.html', controller: AboutController });
$routeProvider.otherwise({ redirectTo: '/' });
}]);
Change the url according to your needs.

Angular Routeprovider: send simple POST request

I'm working on a little Angular example project, using something like this
angular.module('myApp', [
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'view1',
controller: 'Ctrl1'
})
.when('/view1', {
templateUrl: 'view2',
controller: 'Ctrl2'
})
.otherwise({ redirectTo: '/view1'});
});
Now I would like to add a button sending a simple GET "/setDatabaseFlag". No template loading, no new controller. I realized that every call to localhost (my base url for the test) runs through the routeProvider. So I tried to find something like
.when('/setDatabaseFlag', {
$http.get('/setDatabaseFlag');
})
I found an example using
.when('/setDatabaseFlag', {
action: doSomething
})
but $http is not available here. Also "action" seems undocumented.
I guess there must be another approach. Thanks for any hint!

Resources