How to use window.onload in angular js controller? - angularjs

How to use window.onload function inside a controller.
window.onload= function() {
console.log("Hi Page loaded")
};
The controller is not applicable for the full page.
I want to execute a function after my controller loads at-least.

You can use ng-init and invoke your necessary function using the same directive
var app = angular.module('DemoApp', [])
app.controller('akuaController', function($scope) {
$scope.load = function() {
alert("Window is loaded");
}
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="DemoApp" ng-controller="akuaController">
<div ng-init="load()">
</div>
</body>
</html>

Changing the example from Angular $window
Your Controller
angular.module('windowExample', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function(greeting) {
// This would be a starting point
$window.onload(greeting);
};
}]);
Your markup
<div ng-controller="ExampleController" ng-init="ExampleController.doGreeting()">
</div>

//inside your controller
$scope.$on('$viewContentLoaded', function() {
// write here
// either methods or variables
});

Related

AngularJS compile dynamic content

Consider the following webpage:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>First Test</title>
<script src="jquery-3.2.1.min.js"></script>
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp',[]);
function addDiv(){
var div = "<script> \
myApp.controller('myController', function ($scope) { \
$scope.testDynamic = function(){ \
alert('it works!'); \
} \
}); \
<\/script> \
<div ng-controller=\"testController\">{{\"TEST\"}}<button ng-click=\"testDynamic();\">Click Me!</button></div>";
$("body").append(div);
// How to use $compile here???
}
</script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
</head>
<body>
<div>{{"AngularJS"}}</div>
<button onclick="addDiv();">addDiv</button>
</body>
</html>
When the content is appended to the body, how I can load/compile the angularjs part? I have tried to use $compile like:
angular.element('body').injector().invoke(function ($compile, $rootScope) {
$rootScope.$apply(function() {
var scope = angular.element(div).scope();
$compile(div)(scope);
});
});
But without any success. I get the error: "Error: [ng:areq] Argument 'scope' is required..."
Someone can help?
After some tries, I got it working. It was simpler than I thought. After the definition of angular module, I need to add this configuration part:
myApp.config(['$controllerProvider','$compileProvider', '$filterProvider', '$provide', function($controllerProvider, $compileProvider, $filterProvider, $provide) {
myApp.register = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
Then to register the controller coming from ajax:
myApp.register.controller('myController', function($scope) {
$scope.name = "Pippo";
$scope.age = 18;
$scope.go = function(){alert('It works!')}
});
Then, at the success call from ajax add the compile part:
$compile($('#remdiv'))($scope);
Here's the complete code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>First Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
myApp = angular.module('myApp',[])
.controller("mainCtrl", function($scope, $http, $compile, $rootScope){
$scope.addDiv = function(){
var ajaxhtmlcode = '<script> \
myApp.register.controller(\'testc\', function($scope) { \
$scope.name="Pippo"; \
$scope.age=18; \
$scope.go = function(){alert(\'It works!\')} \
}); \
<\/script> \
<div id="remdiv" ng-controller="testc"> \
{{msg}} \
Name:<input ng-model="name" /> \
Age:<input ng-model="age" /> \
<button ng-click="go();">Go!<\/button> \
<\/div>';
$('body').append(ajaxhtmlcode);
$compile($('#remdiv'))($scope);
}
});
myApp.config(['$controllerProvider','$compileProvider', '$filterProvider', '$provide', function($controllerProvider, $compileProvider, $filterProvider, $provide) {
myApp.register = {
controller: $controllerProvider.register,
directive: $compileProvider.directive,
filter: $filterProvider.register,
factory: $provide.factory,
service: $provide.service
};
}
]);
</script>
</head>
<body ng-controller="mainCtrl">
<div>{{"AngularJS"}}</div>
<button ng-click="addDiv();">addDiv</button>
</body>
</html>
1- First of all you have incorrect controller naming, you inject a controller named myController but you trying to call controller named testController
2- you can't declare new controller with this way you have to declare it first and inject the template only via compile method
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>First Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var myApp = angular.module('myApp',[])
.controller("mainCtrl",function($compile,$scope,$rootScope){
$scope.addDiv=function(){
var div = $compile("<div ng-controller=\"test\">{{\"TEST\"}}<button ng-click=\"testDynamic();\">Click Me!</button></div>")($rootScope);
$("body").append(div);
// How to use $compile here???
}
})
.controller('test', function ($scope) {
$scope.testDynamic = function(){
alert('it works!');
}
});
</script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
</head>
<body ng-controller="mainCtrl">
<div>{{"AngularJS"}}</div>
<button ng-click="addDiv();">addDiv</button>
</body>
</html>
Thank you Peter. The first was a copy-paste mistake. I am new in Angular and I am just trying to understand how it works. Your solution works, but what I wanted to point our is this:
What about if I can't define the controller "test" BEFORE? I mean, if the controller definition comes from a html ajax request (I mean if the div variable is populate by an ajax request, controller definition included). That's why I have put the script definition inside the div variable.
Taking back my example...main page:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>First Test</title>
<script src="jquery-3.2.1.min.js"></script>
<script src="angular.js"></script>
<script>
var myApp = angular.module('myApp',[])
.controller("mainCtrl",function($compile,$scope,$rootScope, $http){
$scope.addDiv=function(){
$http({
url: "test.php",
method: "post",
data: '',
responseType: 'text',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function successCallback(response) {
$('body').append(response.data);
}, function errorCallback(response) {
alert(response.statusText);
});
}
});
</script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
</head>
<body>
<div ng-controller="mainCtrl">{{"AngularJS"}}
<button ng-click="addDiv();">addDiv</button>
</div>
</body>
</html>
Where test.php is simply:
<script>
myApp.controller('myController', function ($scope) {
$scope.name = "Pippo";
$scope.age = 10;
});
</script>
<div ng-controller="myController">
Name:<input ng-model="name" />
Age:<input ng-model="age" />
</div>
If I run this code, I can't see the input (name and age) populated as defined in "myController"...

pass data to angular controller from a global function

See example below and the TODO in the send function : How can I assign the label value in the global send function to dropboxController dropbox.label
<!DOCTYPE html>
<html>
<head>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.0-beta.4/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript">
window.onload=function() {
$('#AddIn').append("<div ng-app='dropboxApp' ng-controller='dropboxController as dropbox'>{{dropbox.label}}</div>");
angular.module('dropboxApp', [])
.controller('dropboxController', function () {
var dropbox = this;
dropbox.label = "hello angular";
});
angular.bootstrap($('#AddIn'), ['dropboxApp']);
}
function send(label)
{
//TODO assign label value to dropboxController dropbox.label
}
</script>
</head>
<body>
<div id="AddIn"></div>
<button onclick="send('new label');">Send</button>
</body>
</html>
Use angular.element and get scope of specific dom element and apply label to it.
Change dropbox.label to $scope.label and inject $scope in controller because this and $scope are different. Check 'this' vs $scope in AngularJS controllers
Keep in Mind: Here I have used myDiv which has scope for angular and added id in append div line.
It's better to use ng-click instead of onclick if possible.
window.onload = function() {
$('#AddIn').append("<div id='myDiv' ng-app='dropboxApp' ng-controller='dropboxController as dropbox'>{{label}}</div>");
angular.module('dropboxApp', [])
.controller('dropboxController', function($scope) {
var dropbox = this;
$scope.label = "hello angular";
});
angular.bootstrap($('#AddIn'), ['dropboxApp']);
}
function send(label) {
var scope = angular.element($("#myDiv")).scope();
scope.$apply(function() {
scope.label = label;
})
console.log(scope.label);
}
<!DOCTYPE html>
<html>
<head>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.0-beta.4/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="AddIn"></div>
<button id="myButton" onclick="send('new label');">Send</button>
</body>
</html>

Busy Icon keeps running - AngularJS

I have implemented a code to show a busy icon and this is it
angular.module("app", [])
.controller('UploadCtrl', function ctrl ($scope, $timeout) {
$scope.busy = false;
$scope.submit = function () {
$scope.busy = true;
// pretend to make an http call...
$timeout(function () {
$scope.busy = false;
}, 10000);
};
});
This is the index.html file
<!DOCTYPE html>
<html>
<head>
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="app.js"></script>
<meta charset="utf-8">
<title>Busy Runner</title>
</head>
<body ng-app="app" ng-controller="ctrl">
<button ng-disabled="busy" ng-click="submit()">Submit <i class="fa fa-spinner fa-spin" ng-show="busy"></i></button>
</body>
</html>
When I run the code the busy loader keeps running. Please what could be wrong.
This is the plunk I have made.
view plunk
You reference a controller which not exists. Fix the HTML code
<body ng-app="app" ng-controller="UploadCtrl">
angular.module("app", [])
.controller('UploadCtrl', function ctrl ($scope, $timeout) {
$scope.busy = false;
In the above code you have name your controller as 'UploadCtrl' ,where as, in HTML file
<body ng-app="app" ng-controller="ctrl">
controller is 'ctrl' , due to which it can't load the controller hence the angular part is not executed.
Change your app.js to
angular.module("app", [])
.controller('ctrl', function ($scope, $timeout) {..}
View plunkr
Also I removed ng-disabled from <button ng-disabled="busy" ng-click="submit()">Submit since you are already using $scope.busy = false; as soon as script loads.
Checkout ngController .

AngularJS with loading external page with controller

I have a quick question on loading external page with route. I am quite new to AngularJS.
var app = angular.module('app', []);
$routeProvider.when('/list', {
templateUrl: '/list.html'
})
Load up the page, but within the list.html there is controller defined.
list.html:
<script>
app.controller('test', function(){
console.log('test');
});
</script>
<div ng-controller="test">
</div>
The above code will throw me an error as test is undefined function, unless if i place the app.controller('test') to the parent page.
So i can't place controller on external .html files?
Updated link below:
http://plnkr.co/edit/YC6P9W1VfzX8XOyrynCP?p=preview
You have to create a separate script.js and should load in main html page during execution of main page or during click of the link
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script src="script.js"></script>
<script src="testscript.js"></script>
</head>
<body ng-controller="home">
<h1>Hello Plunker! {{change}}</h1>
Test
<ng-view></ng-view>
</body>
</html>
testscript.js
function test2($scope){
console.log('succeed');
};
script.js
// Code goes here
var app = angular.module('app', ['ngRoute']);
app.controller('home', function($scope){
$scope.change = "change";
$scope.test = function(){
console.log('clicked');
}
});
app.config(function($routeProvider){
$routeProvider.when('/test', {
templateUrl: 'test.html',
controller: function(){
console.log('here');
}
})
});

sharing a var between views/controllers

I know this question has been asked 100s of times but i have yet to succeed in implementing this after reading countless of threads... shame on me.
I know this is a lot of code (sorry). But I just can't find what I'm doing wrong,
So to the problem I want to add something to the list in pat1 then click over to pat2 and see the same list.
Routing;
var routeApp = angular.module('routeApp', ['ngRoute', 'rootMod']);
routeApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/pat1', {
templateUrl: 'partials/pat1.html',
controller: 'pageOneCont'
}).
when('/pat2', {
templateUrl: 'partials/pat2.html',
controller: 'pageTwoCont'
}).
otherwise({
redirectTo: '/pat1'
});
}]);
Controllers & Service:
var rootMod = angular.module('rootMod', []);
rootMod.controller('pageOneCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
}]);
rootMod.controller('pageTwoCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
aService.registerObserverCallback(updateFoo);
//service now in control of updating foo
};
}]);
/* Service */
rootMod.factory('serv', [ function () {
var observerCallbacks = [];
//register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
//call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
}]);
INDEX.html
<!doctype html>
<html lang="en" ng-app="routeApp">
<head>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<li> ONE </li>
<li> TWO </li>
</body>
<!-- SinglePage -->
<div ng-view></div>
</html>
PAT1.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Test</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<div ><!--ng-app="myModule" ng-controller="ContactController">-->
<h1> ONE </h1>
<button ng-click="handleClick"> BROADCAST </button>
<div ng-repeat="item in foo">{{ item }}</div>
</div>
</html>
PAT2.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular Test</title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<div> <!--ng-app="myModule" ng-controller="ContactController">-->
<h1> TWO </h1>
<div ng-repeat="item in foo">{{ item }}</div>
</div>
</html>
JS
Your service is injected as serv in your controllers but you call aService. Use serv instead.
You should use rootMod.service() instead of rootMod.factory() since you are using this and not returning anything in your service function (see this for the difference between factories and services).
There is no serv.foo property. You have to add this.foo = /** something **/; to your service function.
So this should work:
var rootMod = angular.module('rootMod', []);
rootMod.controller('pageOneCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
serv.registerObserverCallback(updateFoo);
// service now in control of updating foo
};
}]);
rootMod.controller('pageTwoCont', [ 'serv', '$scope', function (serv, $scope) {
'use strict';
// Your controller implementation goes here ...
$scope.handleClick = function ($scope, serv){
var updateFoo = function(){
$scope.foo = serv.foo;
};
serv.registerObserverCallback(updateFoo);
// service now in control of updating foo
};
}]);
/* Service */
rootMod.service('serv', [ function () {
var observerCallbacks = [];
// call this when you know 'foo' has been changed
var notifyObservers = function(){
angular.forEach(observerCallbacks, function(callback){
callback();
});
};
// initialize foo here
this.foo = '';
// register an observer
this.registerObserverCallback = function(callback){
observerCallbacks.push(callback);
};
}]);
HTML
You put the ng-view container outside of the body. It has to be inside. Also the path to a view starts with #/ so you have to change your links.
<!doctype html>
<html lang="en" ng-app="routeApp">
<head>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<li> ONE </li>
<li> TWO </li>
<!-- SinglePage -->
<div ng-view></div>
</body>
</html>
Each view only needs the content that should be placed inside the ng-view container. So you mustn't make a complete HTML document.
pat1.html
<h1> ONE </h1>
<button ng-click="handleClick"> BROADCAST </button>
<div ng-repeat="item in foo">{{ item }}</div>
pat2.html
<h1> TWO </h1>
<div ng-repeat="item in foo">{{ item }}</div>

Resources