app.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/demo', {
templateUrl : 'assets/pages/home.html'
})
// route for the sport page
.when('/sport', {
templateUrl : 'assets/pages/sport/home.html',
controller : 'sportController'
});
// route for the sport page
.when('/television', {
templateUrl : 'assets/pages/television/home.html',
controller : 'televisionController'
});
});
I have sportControllerin a file called SportCtrl.js and televisionController in a file called TvCtrl.js, how would I be able to load this into my view while using Routing?
You should correctly add your controller in app namespace and Angular does all things themselves.
For example, working structure for project:
Load Angular, dependencies.
Load your application initializer, configs.
Load other stuff like controllers, directives, services, filters.
Example of controller code:
app.controller('sportController', ['$scope', function($scope){
}])
BTW, for Angular file name means nothing.
You are trying to do a lazy loading of javascript files. This is not an Angular functionality, you have 3 solutions:
use requireJs to load files on-the-fly.
include all your javascript files in html
concatenate all the javascript files in only one file.
I prefer not to use requireJS to prevent one more inclusion and configuration :-)
Related
I have a controllers folders in www/js/controllers where I keep all the controllers needed by my app. But when I start the app all the controllers are loaded at once. Now how can I load only those controllers whose view is being used and keep other controllers at peace.
To dynamically load controllers, you need to use RequireJS.
http://requirejs.org/
Using https://oclazyload.readme.io/docs/with-your-router
Or,
Try this:
If you are using ngRoute:
$routeProvider
.when('/url',
{
templateUrl: '/views/abc.html',
resolve: resolveController('/controllers/abc.js')
});
Using UI-Router:
.state('abc',{
url : '/abc',
templateUrl : 'views/abc.html',
resolve: resolveController('/controllers/abc.js')
})
I don't know what you are trying to ask exactly.
See, JavaScript load All files(even won't take much time) while execute the app. Note it, files load only(allocate the memory) not execute the function except on-fly function. Ex (Angularjs, Jquery, Underscore - the file load first time only but function execute when we use).
Angularjs is JS framework right?. So same like above, here we are telling to execute controller in routing or ng-controler directive as per view, Note the file was loaded before only. In single view we can execute many controllers(ng-controller) as per need.
Create Controllers & Services in IIFE based. It's good.
I am creating web application using Angular js in ES6. I just started learning angular. I have following questions which I couldn't understand much from resources in internet.
1) I am using ui-router for routing based on states. I have following code in my controller
myApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home);
$stateProvider
.state('contact', {
url: '/contact',
templateUrl: 'contact.html',
controller: myContactController
});
};
Contact.html:
<div ng-controller=”myContactController”>
….
</div>
Question:
a) I have specified the controller in my state in js. Should I need to specify the controller using ng-controller in my view also? What is the difference and why its necessary ?
2) I have a base module for my app.
Base module - Index.js :
import subapp1 from ‘./subApp1/index’;
angular.module(“myapp”,[subapp1]);
subApp1/index.js
Export default function(){
Angular. module(“subApp1”,[]);
};
Question:
a) Is this the right way of injecting sub module dependency in to base module?If not which is the best way to inject module dependency in to base module?
b) I would appreciate if I can get best links to understand dependency injection and different scopes in angular js in basic way.
I have specified the controller in my state in js. Should I need to specify the controller using ng-controller in my view also? What is the difference and why its necessary ?
You don't need to use ngController in HTML. Router will fetch HTML template and compile it with specified controller.
I have a base module for my app...
You specify dependent module by its name, so your setup could look like this (note, how you export name property of the Angular module):
export default angular.module('subApp1', [])
.factory('someService', semeService) // For example, attach some module service
.directive('someDirective', someDirective) // ... or some components
.name;
and then
import subapp1 from './subApp1/index';
import subapp2 from './subApp2/index';
angular.module('myapp', [
subapp1,
subapp2
]);
1.a) no, you shouldn't. If you do, you'll have two instances of the controller
2.a) no. First you don't "inject" a module into another module: a module depends on another one, that's all. That has nothing to do with dependency injection. And the syntax for that is
angular.module('myapp', ['subApp1']);
I.e. the elements of the array must be names of module you depend on. And of course, these modules must themselves be defined (before or after, it doesn't matter), using
angular.module('subApp1', []);
2.b) https://docs.angularjs.org/guide
I am minifying an angular project through gulp.This project contains index.html,css,libraries,app.js(Angular module containing routing layer+controllers) and views.
I could easily minify+concat all js files,libraries and css files into one bundle file.HTML files were also easily minified but the problem is i have routing in my app.js which render templateUrl like
.state('dashboard.home', {
url: '/home',
templateUrl: 'app/views/dashboard/home.html'
})
Now,beacause of this routing i cannot minify+concat all html files into one.because each route renders one view with its file name while there will be only one file named bundle.html.
Here,I need a guideline about how to handle this situation.
Thanks Regards
I use the gulp-ng-template for this:
gulpfile.js:
var ngTemplate = require('gulp-ng-template');
....
gulp.task('templates', function () {
return gulp.src(['view1.html', 'view2.html'])
.pipe(ngTemplate({filePath: 'js/tpl.js'}))
.pipe(gulp.dest('test'));
});
ngTemplate combines your views and puts them into the single file js/tpl.js that will look like this:
angular.module('ngTemplates').run(['$templateCache', function($templateCache) {
$templateCache.put('view1.html', '<div class="test">A</div>\n');
$templateCache.put('view2.html', '<div class="test">\n <span>B</span>\n</div>\n');
}]);
Now all you need is to include this file into your index.html. Your views will be available to the angular compiler at their original paths. You don't need to include your original html views into project any more.
You can add this file js/tpl.js to your index.html manually or by using ng-html-replace.
Instead of concatenating all templates into one html file you should use $templateCache angular provider and convert all of your html templates into JavaScript code. By using templateCache you can put all of your teplates into one file and it will work perfectly with routing mechanism. Try this gulp module Gulp ng templates
I'm working with a form that needs to bind HTML to a Rich Text Editor. The best way to store this HTML content would be an HTML file.
I can't quite figure out how to load an HTML template from a file and assign it to a variable.
Directives seem to do be able to do this when working with templateUrl. Was wondering if this there is any low level api in angular to achieve the same thing inside of a controller
Using $templateRequest, you can load a template by it’s URL without having to embed it into your HTML page. If the template is already loaded, it will be taken from the cache.
app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
// Make sure that no bad URLs are fetched. You can omit this if your template URL is
// not dynamic.
var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');
$templateRequest(templateUrl).then(function(template) {
// template is the HTML template as a string
// Let's put it into an HTML element and parse any directives and expressions
// in the code. (Note: This is just an example, modifying the DOM from within
// a controller is considered bad style.)
$compile($("#my-element").html(template).contents())($scope);
}, function() {
// An error has occurred
});
});
Be aware that this is the manual way to do it, and whereas in most cases the preferable way would be to define a directive that fetches the template using the templateUrl property.
All templates are loaded into a cache. There is an injectable $templateCache service you can use to get access to the templates:
app.controller('testCtrl', function($scope, $templateCache){
var template = $templateCache.get('nameOfTemplate.html');
});
ZI'm building an app where based on user preferences/configuration, I'll be loading different modules into the page.
To accomplish this, when the page loads, I run a script which builds a list of script-tags and adds all those tags to the body of the page. I also build a dependency injector list, and include the dependencies when the app is loaded.
I'm delaying app load using by putting
window.name = "NG_DEFER_BOOTSTRAP!";
and then after the script tags are added, I run
angular.element(document).ready(function () {
setTimeout(function(){
angular.resumeBootstrap();
},1000);
});
I have two problems.
First of all, for some reason, if I include angular.js in the configuration file, I get errors referring to angular not being found.
I can see that angular is being downloaded to the browser, but I'm guessing it's a timing issue, as angular takes longer to download than many of the other files.
I was going to just put angular in a regular script tag, but then I found that one of the modules I'm loading requires jQuery and jQuery UI, both to be loaded before angular, so that means more files loaded as scripts, and possibly not needed for that user.
I looked at using require.js and passing the config params to
requirejs.config.paths = //the custom built list from the users configuration file
But, from what I understand, that would also mean I'd need to wrap all of my modules in
requirejs(['jquery', 'angular', 'otherModule'],
function ($, angular, otherModule) {
// my module stuff here
});
Any other suggestions on how to accomplish this? Is there a better AMD than require.js?
I'd post all my code here, but I don't think it would help as the problem is coming from the browser downloading the files after the document is ready.
RequireJs is the best AMD implementation as far as I know.
If you want to specify your modules, you'd better to wrap your moduls in define calls:
define(['jquery', 'angular', 'otherModule'],
function ($, angular, otherModule) {
// DO NOT FORGET TO RETURN YOUR MODULE!
});
Also, why don't you start your applicaiton on domReady? You may use this requirejs plugin.
Here is a basic requirejs configuration for your case:
requirejs.config({
paths : {
jquery : 'libs/jquery',
jqueryUi : 'libs/jqueryui',
angular : 'libs/angular'
},
shim : {
angular : {exports : 'angular', deps : ['jquery']},
jqueryUI: {exports : '$', deps : ['jquery']}
},
map : {
'*' : {
domReady : 'require-plugins/domReady'
}
}
});
requirejs(['domReady!', 'angular'], function(document, angular) {
//Thank to domReady!, this callback executes on domReady events. And no need in jquery or angular:)
});