Adding app.js to angular application - javascript

I'm triying to add bootstrap ui modules to an angular project. In every tutorial I read that after download the module i'm supposed to add a directive (angular.module(for example: 'App', ['ui.carousel']) to certain file that in some forums i've read is called app.js. This file doesnt exist in my project. The question is: Should I create it? Where? Is a controller necesary? How is the flow that this must follow? Then I should add it to the index.html?

Getting advanced here with components without even knowing the basics. I recommend starting with just controllers (without components). But, here is a basic example of how scripts are added:
<!DOCTYPE html>
<html ng-app="myApp">
<!-- Adding scripts here. The order matters: angular.js first, then its dependancies, e.g. ui-bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<body>
<div>
<!-- main body -->
<div>
<hello-world name="World"> </hello-world>
</div>
</div>
<!-- ng-template simulates a separate file -->
<script type="text/ng-template" id="my_component.html">
<input class="form-control" ng-model='$ctrl.name'><br><span>Hello {{$ctrl.name}}, I'm {{$ctrl.myName}}!</span>
</script>
<!-- This script can be also written as:
<script src="/app.js"></script>
if the file `app.js` is located in root directory of the server,
which should contain the AngularJS code below
-->
<script>
var app = angular.module('myApp', ['ui.bootstrap']); // injected dependancies
app.component("helloWorld", {
templateUrl: "my_component.html",
/* component template */
bindings: {
name: '#'
},
controller: function() {
this.myName = 'Karolyn'; // use of `this` requires `$ctrl` in the template HTML
}
});
</script>
</body>
</html>

Related

Inclusion of Angular into HTML is being tricky

I am trying to extend my knowledge of JS by learning angular or at the very least get an understanding of angular. I am trying to go through this tutorial but I can not get my downloaded version of angular to load.
I have tried replacing my copy of of the js file with the one included on the GitHub for the tutorial and that works but when I try and link to my local copy it breaks.
This code doesn't work but as soon as the angular file is replaced with one from the repo it works. The two copies of angular are in the same lib folder and I have double checked the names. I have also tried using Google's CDN but that doesn't work either.
Any thoughts on why angular would be acting up this way?
<!doctype html>
<html ng-app>
<head>
<title>Sample AngularJS Controller</title>
</head>
<body>
<div ng-controller="TestCtrl">
<h1>{{title}}</h1>
<input type="text" ng-model="title">
</div>
<script src="lib/jquery-v1.11.1.js"></script>
<script src="lib/angular.js"></script> <!--Fresh Download-->
<!--If I replace the angular.js link with this it works.-->
<!--<script src="lib/angular-v1.2.22.js"></script>-->
<script>
function TestCtrl($scope) {
$scope.title = "Example title! (Change or delete me)";
};
</script>
</body>
</html>

create controller in ng-view page

I want to manage my controller specific to an ng-view page, therefore I put the controller in ng-view page and used that controller specific to that page only. However, the code does not show what it should show from that controller.
Here is my case.
I split my code into 3 files, which are "mainfile.php", "page1file.php", and "page2file.php". "mainfile.php" contains main page which routes to page 1 and page 2. To compare the results, I created different conditions for those 2 pages. "page1file.php" uses controller which has been defined in "mainfile.php", while "page2file.php" uses controller which is defined in the page itself.
In this circumtances, "page1file.php" successfully shows what I want, but "page2file.php" does not show what it should show. Please help me and give a very simple explanation and a simple solution since I'm very new to angularjs.
Here is my code. You can just copy them and run it on your php server.
mainfile.php :
<!DOCTYPE html>
<html>
<head>
<title>learn angular routing</title>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
<script type="text/javascript">
function routeReload($scope) {
$scope.routeReloading = function(){
window.location.reload();
};
}
routeReload.$inject = ['$scope'];
function routeConfig($routeProvider) {
$routeProvider
.when('/one',{
templateUrl:'page1file.php'
})
.when('/two',{
templateUrl:'page2file.php'
})
;
}
routeConfig.$inject=['$routeProvider'];
function testOne($scope) {
$scope.name = "page one";
}
testOne.$inject = ['$scope'];
var testNgView = angular.module('testNgView',['ngRoute']);
testNgView.config(routeConfig);
testNgView.controller('routeReload',routeReload);
testNgView.controller('testOne',testOne);
</script>
</head>
<body>
<div ng-app="testNgView">
<div ng-controller="routeReload">
View page <a ng-click="routeReloading();" href="#one">one</a> or
<a ng-click="routeReloading();" href="#two">two</a>
<div ng-view></div>
</div>
</div>
</body>
</html>
page1file.php :
<div ng-controller="testOne">
This is {{name}}
</div>
page2file.php :
<script type="text/javascript">
function testTwo($scope) {
$scope.name = "page two";
}
testTwo.$inject = ['$scope'];
testNgView.controller('testTwo',testTwo);
</script>
<div ng-controller="testTwo">
This is {{name}}
</div>
I don't think you can inline script modules in your view templates. Have a look at this working version of your app, the way I would organize it:
http://plnkr.co/edit/nSsagK1Y04akNJyMToah?p=preview
You can use .php files in place of the .html files, that shouldn't make a difference.
So your main file should look something like this:
<!DOCTYPE html>
<html>
<head>
<title>learn angular routing</title>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
</head>
<body>
<div ng-app="testNgView">
View page one
or two
<ng-view></ng-view>
</div>
<script src="app.module.js"></script>
<script src="app.routes.js"></script>
<script src="views/page1/controller.js"></script>
<script src="views/page2/controller.js"></script>
</body>
</html>
If your goal is to use PHP to dynamically render your controllers, see the answer to this SO question: Angularjs: server side (php) rendering and data binding client side after an event
You may also be interested in this article, about loading Angular components after the application has been bootstrapped: http://www.bennadel.com/blog/2553-loading-angularjs-components-after-your-application-has-been-bootstrapped.htm
TL;DR: You would need to store a reference to $controllerProvider in the config phase, and then call $controllerProvider.register('MyController', MyController) in your inline script. I'm not sure how I feel about that though...

Angularjs app not bootstrapping without module

I am new to angularjs and this might sound very silly but I want to know why my angularjs app won't bootstrap without making a module even though egghead.io and several tutorials showing otherwise.
Here is my HTML template
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.1" src="https://code.angularjs.org/1.4.0-beta.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="controller.js"></script>
</head>
<body>
<div ng-controller="HelloController">
<p>{{greeting.text}}, World</p>
</div>
</body>
</html>
And the controller.js file which DOESN'T WORKS
function HelloController($scope) {
$scope.greeting = { text: 'Hello' };
}
When i register the module [and naming the ng-app as 'hello' ofcourse] and write a controller it works
angular.module('hello', []).controller('HelloController', function($scope) {
$scope.greeting = { text: 'Hello' };
});
I just want to know the reason for this behavior.
Thanks in anticipation.
This is a breaking change of angular 1.3. You can see a list of breaking changes here
Because of this change, you cannot use global functions as a controller. You can override this behavior by using allowGlobals (More info here) but I won't recommend that.

Dynamic Directive loading using AngularJS - Error: Access to restricted URI denied

I'm currently developing a small educational project using HTML5, CSS, JS and AngularJS.
Problem: Loading of a AngularJS Directive in my index.html file
Error code [1] - Local browser
Error: Access to restricted URI denied
Some answers to this question, suggested to deploy the project on a web server. I did it and the error was very interesting:
Error code [2] - Webserver
Failed to load resource: the server responded with a status of 404 (Not Found)
File structure
app/
---- app.js
---- components/
---------- view1/
-------------- fullView.html
-------------- fullViewApp.js
-------------- partialViews/
------------------ partsOfFullView.html
------------------ morePartsOfFullView.html
assets/
---- libs/
---- css/
---- ...
---- ...
index.html
Code
index.html
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<title>My Example</title>
<!-- CSS -->
<link href="./assets/css/bootstrap.min.css" rel="stylesheet">
<link href="./assets/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<!-- Libs -->
<script src="./assets/libs/jquery-2.1.1.min.js"></script>
<script src="./assets/libs/angular.min.js"></script>
<script src="./assets/libs/bootstrap.min.js"></script>
<script src="./assets/libs/moment-with-locales.js"></script>
<script src="./assets/libs/bootstrap-datetimepicker.min.js"></script>
<!-- App's modules -->
<script type="text/javascript" src="./app/app.js"></script>
<script type="text/javascript" src="./app/components/view1/fullViewApp.js"></script>
</head>
<body ng-controller="MyAppTranslationCtrl">
<!-- my custom directive -->
<qwe></qwe>
</body>
</html>
app.js
angular.module('MyApp', ['MyApp.View1App'])
.controller('MyAppTranslationCtrl', function($scope) {
console.log('-> MyApp Translation example');
});
fullView.html
<div ng-app="MyApp.View1App" ng-controller="...">
<div ng-controller="...">
<!-- content, other directives, etc... -->
...
...
</div>
</div>
fullViewApp.js
angular.module('MyApp.View1App', [])
.directive('qwe', function() {
return {
restrict: 'E',
templateUrl: 'fullView.html'
}
});
Sorry for the long post, but I tried to make it clear, understandable and easier to find the problem.
After all I am stuck on this error and I can't get it fixed.
I have tried to move all the files in one folder and it magically works! But when I separate them in different folders = ERROR. I can't get it up and running!
Please assist me :)
############################ ANSWER
After changing the relative paths to have a full qualifier before them, as suggested in the next post, everything was fine!
Thank you!
Assuming this is throwing the error:
angular.module('MyApp.View1App', [])
.directive('qwe', function() {
return {
restrict: 'E',
templateUrl: 'fullView.html'
}
});
You need to use the full path.
angular.module('MyApp.View1App', [])
.directive('qwe', function() {
return {
restrict: 'E',
templateUrl: 'app/components/view1/fullView.html'
}
});

AngularJS multiple ngApps each with its own ngRoute definitions, lazyloaded and bootstrapped on one page

My question comes from the need to lazy load different/separate ngApps on one page(bootstrapping them with angular.bootstrap), each of them using its own ngRoute definitions(defined in such a way that they do not overlap each other).
Now I have a working plunkr example and all seems to function well, but somehow I have the feeling that this is not the correct approach so that's why Im asking here for advice.
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="container">
<div class="col-xs-6 well" id="app1">
<h3>App1</h3>
Route 1
Route 2
Route 3
<div class="well" ng-view></div>
</div>
<div class="col-xs-6 well" id="app2">
<h3>App2</h3>
Route 1
Route 2
Route 3
<div class="well" ng-view></div>
</div>
</div>
<script type="text/javascript" src="https://code.angularjs.org/1.2.21/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.2.21/angular-route.min.js"></script>
<script>
var app1 = angular.module('app1', ['ngRoute']);
app1
.config(function($routeProvider) {
$routeProvider
.when('/:app/:param', {
template: 'app = {{app}}, param = {{param}}',
controller: 'Ctrl1'
})
})
.controller("Ctrl1",['$scope','$routeParams', function($scope,$routeParams) {
$scope.app = $routeParams.app;
$scope.param = $routeParams.param;
}]);
var app2 = angular.module('app2', ['ngRoute']);
app2
.config(function($routeProvider) {
$routeProvider
.when('/:app/:param', {
template: 'app = {{app}}, param = {{param}}',
controller: 'Ctrl2'
})
})
.controller("Ctrl2", ['$scope','$routeParams', function($scope,$routeParams) {
$scope.app = $routeParams.app;
$scope.param = $routeParams.param;
}]);
angular.bootstrap(document.getElementById("app1"), ['app1']);
angular.bootstrap(document.getElementById("app2"), ['app2']);
</script>
</body>
</html>
http://plnkr.co/edit/Y7A9bc3bDUyAXIS13JMZ?p=preview
FYI: I have already checked out ui-router to load separate states on one page, but it all requires for the source code to be loaded upfront(and have a single app.config with all routes in it) which is something I do not want as the Project is quite huge. So for the sake of keeping it simple and modular Im looking for something like the above example.
UPDATE to answer HockeyJ question:
OK I will try to keep this as short as possible. Very basically put - as I said the project could potentially become quite huge, from source code and module dependency perspective. This is why I want to make it in such a way, that each module can be totally separate App, able to be injected at any place and tested separately(thats not really an issue with AnJS). In the same time however the whole project, should be a single page app. As such there should not be screen reloads(to load an App jscript files) etc. Hence comes the lazy loading of scripts on demand and bootstrapping apps to DOM elems. The only possible intersection point of all apps is the URL routing which has strict naming convention for routes i.e. /reports/whatever ; /transactions/whatever etc. and should be managed by ngRoute.
UPDATED:
Checkout overmind project for angular and the demo here
Shows a project broken up into several apps: nav, home, profile, and admin. The nav app is always on the page and is the only app bootstrapped on pageload.
Just take routing out of angular and use something like sammy.js , history.js etc for client side routing.
Use
angular.bootstrap(module, node)
in the routes of your sammy handlers
Also you might want to take a look at react.js (with or without flux) and tide it up with sammy the same way. Consider this example from todombc : https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/react

Categories