sharing a var between views/controllers - angularjs

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>

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

Code throws error of 'controller with name 'aditya' not registered'

Html code:
<div class="container" ng-controller="aditya"></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="controllers/controller.js"><script>
And calling it in controller.js file
function aditya() {
console.log("Hello World from controller")}
I think your controller name does not match with controller you have assigned in js
angular.module('aditya', function (){
function your_function_name() {
console.log('Hello world from controller')
}
});
Causes for this error can be:
Your reference to the controller has a typo. For example, in the
ngController directive attribute, in a component definition's
controller property, or in the call to $controller().
You have not
registered the controller (neither via Module.controller nor
$controllerProvider.register().
You have a typo in the registered
controller name.
<html>
<head>
<title>Angular JS Controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="controllers/controller.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="aditya">
</div>
</body>
</html>
controller.js
var mainApp = angular.module("mainApp", []);
mainApp.controller('aditya', function($scope) {
console.log("Hello World from controller");
});
Update
<html>
<head>
<title>Angular JS Controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('aditya', function($scope) {
$scope.test = "Controller Testing";
console.log("Hello World from controller");
});
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="aditya">
{{test}}
</div>
</body>
</html>

How to use window.onload in angular js controller?

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
});

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>

How do you set up a relationship between properties of two angular controllers?

Say I've got AdamController as adam and AnujController as anuj. I want anuj.anujProp to have a j appended to it every time adam.adamProp changes.
How could this be done? What is the best way?
Here are 4 possible ways that I came up with. I ranked them in the order that I personally feel is best.
Events - http://plnkr.co/edit/4AD8e47DaOSuutrphIkN?p=preview
Method on a Factory - http://plnkr.co/edit/Vixab8LjDtow5YYfnlMV?p=preview
Factory + $watch - http://plnkr.co/edit/1zVZ9EDarCGPOMZvrJMd?p=preview
$scope inheritance - http://plnkr.co/edit/3b7tzPI5Y4CcwWYXUk25?p=preview
The $scope inheritance approach just feels "messy". I like the event driven approach over the factory approaches because I feel like there's a sort of overhead associated with the factories, and if it's only going to be used for this one purpose, the overhead isn't worth it. Plus, this just seems to be exactly what events are for. I put (2) ahead of (3) because the $watch hurts performance.
Events
angular
.module('app', [])
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function AdamController($rootScope) {
var vm = this;
vm.prop = 'adam';
vm.update = function() {
$rootScope.$broadcast('propChange');
};
}
function AnujController($scope) {
var vm = this;
vm.prop = '';
$scope.$on('propChange', function(event) {
event.currentScope.anuj.prop += 'x';
});
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='adam.prop' ng-change='adam.update()'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.prop }}</p>
</div>
</body>
</html>
Method on a Factory
angular
.module('app', [])
.factory('Factory', Factory)
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function Factory() {
return {
anujProp: 'anuj',
update: function() {
this.anujProp += 'j';
}
};
}
function AdamController(Factory) {
var vm = this;
vm.factory = Factory;
}
function AnujController(Factory) {
var vm = this;
vm.factory = Factory;
}
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='initial' ng-change='adam.factory.update()'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.factory.anujProp }}</p>
</div>
</body>
</html>
Factory + $watch
angular
.module('app', [])
.factory('Factory', Factory)
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function Factory() {
return {
shared: 'shared',
related: 'related'
};
}
function AdamController(Factory) {
var vm = this;
vm.factory = Factory;
}
function AnujController(Factory, $scope) {
var vm = this;
vm.factory = Factory;
$scope.$watch('anuj.factory.related', function(newValue, oldValue, scope) {
scope.anuj.factory.related = newValue.toUpperCase();
});
}
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='AdamController as adam'>
<input ng-model='adam.factory.shared'>
<input ng-model='adam.factory.related'>
</div>
<div ng-controller='AnujController as anuj'>
<p>{{ anuj.factory.shared }}</p>
<p>{{ anuj.factory.related }}</p>
</div>
</body>
</html>
$scope inheritance
angular
.module('app', [])
.controller('AdamController', AdamController)
.controller('AnujController', AnujController)
;
function AdamController($scope) {
var vm = this;
vm.adamProp = 'adam';
vm.update = function() {
var anuj = $scope.$parent.$$childTail.anuj;
anuj.anujProp += 'j';
};
}
function AnujController() {
var vm = this;
vm.anujProp = 'anuj';
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="AdamController as adam">
<input ng-model="adam.adamProp" ng-change="adam.update()" />
</div>
<div ng-controller="AnujController as anuj">
<p>{{ anuj.anujProp }}</p>
</div>
</body>
</html>

Resources