Running Controller in Angular and phpStorm - javascript

I'm new to angular and I'm learnign it using phpStorm tool.
It looks like I've done everything right, but I still can't get the right result when I execute the following html and Javascript codes, I did lots of researches on this and made sure that I followed the solutions provided without getting a step ahead:
index.html
<!DOCTYPE html>
<html ng-app="myApp" >
<head >
<title>Ang Tut</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Groups</h1>
<div ng-controller="GroupController">
<ul>
<li ng-repeat="group in groups" ng-model="group.group_name">
{{group.group_name}}
</li>
</ul>
</div>
</body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</html>
and my app.js file:
var app = angular.module("myApp", []);
app.controller("GroupController", function($scope){
$scope.groups= [
{"id":"144","group_name":"new grouppp"},
{"id":"303","group_name":"Combination group"},
{"id":"323","group_name":"pcb"}
]
});

Same code is working, angular.min.js may not included properly, access your index.html file using http:// instead of file://
var app = angular.module("myApp", []);
app.controller("GroupController", function($scope){
$scope.groups= [
{"id":"144","group_name":"new grouppp"},
{"id":"303","group_name":"Combination group"},
{"id":"323","group_name":"pcb"}
]
});
<!DOCTYPE html>
<html ng-app="myApp" >
<head >
<title>Ang Tut</title>
<meta charset="UTF-8">
</head>
<body>
<h1>Groups</h1>
<div ng-controller="GroupController">
<ul>
<li ng-repeat="group in groups" ng-model="group.group_name">
{{group.group_name}}
</li>
</ul>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</html>

I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem

You have to include ngRoute in your project.
<script src="angular-route.js"> You can get this file here.
And in your app.js
var app = angular.module("myApp", ['ngRoute']);
And it will start working correctly.
Now, the reason this works in jsFiddle but not locally.
That is because if you look at left pane in jsFiddle under Frameworks & Extensions, you will find the selected option to be no wrap - in <body>
Which means that the code you write in javascript block of js fiddle will be placed inside the body tag the the generated html and therefore, you don't need ngRoute.
But while running locally, I see you have your module initialization in different file viz. app.js that is where ngRoute comes into picture.
In older versions of angular ngRoute was included in angular itself. But in latest versions (not sure from which versions) the ngRoute module is provided separately.

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...

NG include scope

I've read tons regarding ng-include scope issue but none seem to address the simple thing I'm trying to do. Hope someone can clarify.
This is a simplified version of what I'm trying to do but encapsulates the issue .
Here's the main page
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head >
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/simple-sidebar.css" rel="stylesheet">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/angular.min.js"></script>
<script>
var app = angular.module('MyApp', []);
</script>
<div ng-include="'/Menu.html'" ></div>
</body>
</html>
and here is Menu.html
<div id="sidebar-wrapper" ng-app="MyApp" ng-controller="MenuController">
<ul class="sidebar-nav">
<li class="sidebar-brand">
<a href="#">
Header
</a>
</li>
<li>
Sign In
</li>
<li ng-repeat="menuItem in MainMenu.Labels">
{{menuItem}}
</li>
</ul>
<script>
app.controller('MenuController', function($scope) {
$scope.MainMenu = {"Labels":["Status","Setup"]} // this code never executes
});
</script>
</div>
How can I create a variable for binding inside menu.html... I can do this outside , but our engine will be generating the menu when that file is requested..
The issue you are facing is not actually a scope issue in this case, but rather how you are setting up your angular app. By putting the code that initializes and assigns the controller to the app in the include, the MenuController is undefined when angular tries to compile the newly included view, and the code will never run, and actually should be throwing errors in the console. I would recommend one of the following:
Remove the angular script from the templates themselves and set them up in their own files with the entire app and its modules set up to be initialized before runtime.
While i don't fully understand what you mean by Engine generating the Menu - it sounds like you are trying to use a template language to actually generate the literal javascript between the script tags from a view model of sorts to set the values. If this is the case, I would advise against this and use an angular service and the $http provider to make an ajax call to set those values in memory.
If you must structure your app this way, you will have to look into lazy loading the controller with a library like this one - https://github.com/matys84pl/angularjs-requirejs-lazy-controllers. I have not used it but from a quick browse through the readme, it appears it might be able to solve your issue will maintaining the structure of your app.

Gracefully error out template variables in Angular JS

When there is a line of code in an Angular application that causes an error, the entire template is broken.
For example, this code (which results in an error when we try to assign a value to foo.bar):
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My App</title>
</head>
<body>
<div class="container" id="home" ng-controller="MainCtrl">
<h1>Message: {{hello_msg}}</h1>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular.js"></script>
<script>
var myApp = angular.module('myApp', ['myApp.controllers']);
angular.module('myApp.controllers', []).
controller('MainCtrl', ['$scope', function ($scope) {
var hello_msg = 'Hello!';
$scope.hello_msg = hello_msg;
// malformed JS
foo.bar = 'app breaks';
}]);
</script>
</body>
</html>
Completely breaks the page, and it looks like this:
Is there some configuration option that I can add to my Angular app so that the page erorrs out more gracefully? Specifically, the variables in the templates that are wrapped in {{ and }}, do not display them at all if there is an error in the app.
One way to error out more gracefully would be to use:
<div ng-bind-html="hello_msg">
The ugly {{hello_msg}} would not display when the foo.bar breaks the app.
Please check this plunker that proves the point
IMPORTANT NOTE
To use ng-bind-html instead of the curly brackets, you need to include ng-sanitize in your module.

How to use a controller in an other file in Angularjs

I'm used to code with Java with many files with object paradigm and MVC pattern with packages.
And I begin with AngularJS, I'm trying to enable a simple index.html who use a controller in javascript file but doesn't work.
my html file : index.html
<html ng-app="carre">
<head>
<script src="js/angular.js"></script>
<script src="js/CalculCtrl.js"></script>
<script>
var ctrl = angular.module('carre',[]);
</script>
</head>
<body ng-controller="CalculCtrl">
<div>{{2+2}}</div>
<p>{{temps}}</p>
</body></html>
My javascript file as controller located at js/CalculCtrl.js
carre.controller('CalculCtrl', function($scope)
{
$scope.temps = 'pluie';
}
)
What's wrong here please ?
Thanks in advance.
Rename carre.controller(...) to ctrl.controller
Ctrl is the name of the variable holding a reference to your module, carre is the name you have given it for reference in the ng-app directive.
Edit: Also, I recommend you get the Batarang extension for Chrome, it adds a page to the Developer Tools for debugging Angular apps. Very helpful tool to have.
You should invert the file inclusion and the module declaration:
<html ng-app="carre">
<head>
<script src="js/angular.js"></script>
<script>
var carre = angular.module('carre',[]);
</script>
<script src="js/CalculCtrl.js"></script>
</head>
Also, because you are using a variable called carre inside CalculCtrl.js, you should rename the variabile assignd when creating the module, from ctrl to carre:
var carre = angular.module('carre',[]);
You have created module ctrl and using carre to refer it.And script sequence is wrong.The right answer is
index.html
<html>
enter code here<html ng-app="carre">
<head>
<script src="js/angular.js"></script>
<script>
var carre = angular.module('carre',[]);
</script>
<script src="js/CalculCtrl.js"></script>
</head>
<body ng-controller="CalculCtrl">
<div>{{2+2}}</div>
<p>{{temps}}</p>
</body></html>
CalculCtrl.js
carre.controller('CalculCtrl', function($scope)
{
$scope.temps = 'pluie';
}
);
As an alternative to the other answers you could create your CalculCtrl in it's own module and then depend on that module when declaring carre.
angular.module('Calcul', [])
.controller('CalculCtrl', function($scope)
{
$scope.temps = 'pluie';
}
);
and then for carre
angular.module('carre', ['Calcul']);
In this way you don't need to re-order your script tags as they are
the answer is here
index.html
<html ng-app="AppliName">
<head>
<--! we load angularjs -->
<script src="js/angular.js"></script>
<--! we load our controller in an other javascript file -->
<script src="js/mesControllers.js"></script>
</head>
<body ng-controller="myCtrl">
<p>time is : {{temps}} </p>
</body>
</html>
mesControllers.js located at js/mesControllers.js
var AppliName = angular.module('AppliName', []);
AppliName.controller('myCtrl', function ($scope) {
$scope.temps = 'pluie';
});
run and Keep calm it working now ;p

Categories