Is there something like initialize module once in angular? - angularjs

Can I have loading some data once in angular module? I tried to use .run() but it gets called whenever page is accessed. For Example: say there are 2 html pages belonging to same module:
TestPage1.html:
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/angular.min.js"></script>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<p><a ng-href="TestPage2.html">Go to Page2</a></p>
</body>
</html>
TestPage2.html:
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/angular.min.js"></script>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<p><a ng-href="TestPage1.html">Go to Page1</a></p>
</body>
</html>
app.js:
var myApp = angular.module('myApp', []);
var cnt = 0;
myApp.run(['$rootScope', '$http', function(scope, $http) {
if(scope.loggedIn == undefined || scope.loggedIn == null) {
$http.get('rest/userData').success(function(data) {
cnt++;
alert(cnt);
scope.loggedIn = true;
});
}
}]);
When I navigate from one page to another this .run() is getting called again and again with cnt as 1. Is it possible to have it called once in life- time of module getting initialized? Or what is the other way?

It seems you are missing some basics such as a controller. The typical angular setup is having an ng-view for your app and loading the other pages via routing. Here is a simple example:
http://beta.plnkr.co/edit/RnZWeWxTJFri49Bvw50v?p=preview
app.js
var app = angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'TestPage1.html', controller: Page1Ctrl});
$routeProvider.when('/view2', {templateUrl: 'TestPage2.html', controller: Page2Ctrl});
$routeProvider.otherwise({redirectTo: '/view1'});
}]).run(function () { // instance-injector
alert('only run on first page load this is where you load data or whatever ONE time'); // this only runs ONE time
})
function MainCtrl($scope) {
$scope.name = 'main';
}
function Page1Ctrl($scope) {
$scope.name = 'page 1';
}
function Page2Ctrl($scope) {
$scope.name = 'page 2';
}
HTML:
<html ng-app="myApp" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
This is the main page. Main nav:
<a ng-href="#/view1">Go to Page1</a>
<a ng-href="#/view2">Go to Page2</a>
<div ng-view></div>
</body>
</html>
You will notice in the html there is an ng-view, when a route is encountered such as #/view the routeprovider looks it up and provides the correct template and calls the appropriate controller. I believe this is the kind of setup you are trying to achieve.

Related

Not able to load angular view

I have index file :
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="./js/jquery-1.9.1.js"></script>
<script src="./js/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="./Controller/homingController.js"></script>
<link rel = "stylesheet" href = "./css/angular-material.min.css">
<link rel="stylesheet" href="./css/bootstrap-theme.min.css">
<link rel = "stylesheet" href = "./css/materialize.min.css">
<link href="./css/icon.css" rel="stylesheet">
<link rel ="stylesheet" href="./css/Main.css">
<title>Home Application</title>
</head>
<body ng-app="myApp">
<div class="navbar">
Home
about
</div>
<div ng-view></div>
<script>
</script>
</body>
</html>
My Controller
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when("/home", {
templateUrl: "home.html"
, controller: "homingController"
});
});
app.controller('homingController', function ($scope, $http) {
alert ("Hello");
var url = "workingURL"; /// changed function to a simple string message to
test
$scope.message = "Hello Liberals";
});
My View home.html
<h1>Hello</h1>
{{message}}
Neither its seems going into homingController and alerting Hello .
Nor its not loading view, infact when I debug its not going to controller. Is there anything I missing here ?
Please refer following link:
you need to just seperate js code and html code
https://jsfiddle.net/ok9he9b9/2/

AngularJS controller won't load into partial

I'm trying to create a login/signup site in order to learn how to separate controllers and partial views, but I'm not sure why my 'LoginController' isn't being injected. Feel free to provide any other feedback.
app.js
angular.module('Registration', ['ngRoute'])
.config(['$routeProvider', ($routeProvider) => {
$routeProvider
.when('/login', {
templateUrl: 'app/login/login.html',
controller: 'LoginController'
})
.otherwise({ redirectTo: '/login' });
}]);
LoginController.js
angular.module('Registration')
.controller('LoginController', ['$scope', ($scope) => {
$scope.message = 'Does this work?';
}]);
login.html
<div class="col-md-offset-3 col-md-6">
{{ message }}
</div>
index.html
<!doctype html>
<html ng-app="Registration">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sup?</title>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="assets/css/styles.css">
</head>
<body>
<div class="container">
<div class="row">
<div ng-view></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/angular.min.js"></script>
<script src="assets/js/angular-route.min.js"></script>
<script src="app/app.js"></script>
<script src="app/login/LoginController.js"></script>
</body>
</html>
server.js
var express = require('express');
var app = express();
app.use(express.static('./public'));
app.listen(3000, () => {
console.log('Listening on port 3000.');
});
Directory Structure
Turns out you can't use an arrow function in the controller! Totally didn't mean to answer my own question.
Found the answer here: https://github.com/angular/angular.js/issues/14814
Just try to reach to your login route like http://localhost:8080/#/login

Angular not run directive

Why is that when I run my Angular app, I don't get directive running?
Example code:
var app = angular.module("app",['mgcrea.ngStrap','layout.menu']);
app.controller('MainController', ['$scope','$timeout', function($scope,$timeout){
$timeout(function(){console.log("ready")});
}]);
var menu = angular.module('layout.menu', [])
.controller('MenuController', ['$scope', function($scope){
console.log("controller");
}])
.directive('menuDir', ['$window', function($window){
console.log("directive");
return function (scope, element) {
console.log("return directive");
};
}]);
HTML:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="assets/libs/bootstrap/dist/css/bootstrap.min.css">
<script src="assets/libs/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="assets/libs/angular/angular.js"></script>
<script type="text/javascript" src="assets/libs/angular-strap/dist/angular-strap.js"></script>
<script src="assets/libs/angular-strap/dist/angular-strap.tpl.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="MainController">
<div class="list-group mainmenu" id="mainmenu" ng-controller="MenuController"></div>
</body>
</html>
When I run the app, I get the controller output, but no output from directive. Why? How can I fix it?
Directives/Services/Factories in angularJs are lazily instantiated.
They will be processed only when we use them.
Use the menuDir directive in your markup, then you will see the console statement written inside your directive.

Angular otherwise not working

So on load to the base page, I'm expecting the page to redirect to: http://myurl.com/index.php#/search
Currently nothing happens...any ideas?
<!doctype html>
<html ng-app="appDep">
<head>
<meta charset="utf-8">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular-route.js"></script>
<script>
var app = angular.module('appDep', ['ngRoute']);
app.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/search/:sig?', {
templateUrl: 'blablabla',
controller : 'notYetCreated'
}).otherwise({
redirectTo : '/search'
});
} ]);
app.controller('notYetCreated', function($scope,$log,$http,$q,$routeParams, $location) {
console.log('test')
});
</script>
</head>
<body>
HI
<script type="text/ng-template" id="blablabla">
TEST
</script>
</body>
</html>
Add <div ng-view></div>

ng-view doesn't show anything in my angularJS app

I'm new in Angular. I have a simple angular app and I try to see how routing works in angular. I have three links which I want angular to change the URL for me and show the right view for each link in the same single page application.
This is my code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Agent Portal</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/justified-nav.css" rel="stylesheet">
</head>
<body ng-app="AgentApp">
<div class="container" ng-controller="createdPackagesController">
<div class="masthead">
<h3 class="text-muted">Project name</h3>
<ul class="nav nav-justified">
<li >Created Packages</li>
<li >Reserved Packages</li>
<li >Published Packages</li>
</ul>
</div>
<div ng-view></div>
</div>
<script src="js/controllers.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
</body>
</html>
controllers.js
var AgentApp = angular.module('AgentApp', [ngRoute]);
AgentApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
controller: 'createdPackagesController',
templateUrl: 'views/createdpackages.html'
})
.when("/reservedPackages", {
controller: "reservedPackagesController",
templateUrl: "views/reservedpackages.html"
})
.when("/publishedPackages", {
controller: "publishedPackagesController",
templateUrl: "views/publishedpackages.html"
}).otherwise({ redirectTo: '/'});
}]);
// create the controller and inject Angular's $scope
AgentApp.controller('createdPackagesController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
AgentApp.controller('reservedPackagesController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
AgentApp.controller('publishedPackagesController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
The app doesn't show anything for ng-view. What should I change?
I followed many examples that are online, but don't know what I'm missing.
[I have seen many similar questions here, but they had their own specific problem (jquery related, browser problem, ..).]
Thanks,
Your controller.js has to be called after angular
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-route.js"></script>
<script src="controller.js"></script>
and you have to declare the ngRoute like this
var AgentApp = angular.module('AgentApp', ['ngRoute']);
Here is a [plunker] (http://plnkr.co/edit/PBC3MWGbuHHn3IwH2cXw?p=preview)
you have to include $route into your controller next to $scope
AgentApp.controller('createdPackagesController', function($scope, $route)
and do so for evey controller and everything will be fine

Resources