can't bind scope variables in angularjs - javascript

I have these files:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Gestore Anagrafica</title>
</head>
<body>
<div>
<h3>Insert new person</h3>
<div ng-app="Person" ng-controller="PersonController">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Age: <input type="number" ng-model="age"><br>
<br>
Full Name: {{fullName()}} <br>
Is major: {{isMajor()}} <br>
<button ng-click="add()">Add Person</button>
</div>
</div>
<script type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" src="js/RegistryService.js"></script>
<script type="text/javascript" src="js/PersonController.js"></script>
</body>
</html>
js/RegistryService.js:
angular.module('RegistryService', []).
service('registry', function()
{
this.people = [];
this.add = function(person)
{
people.push(person);
}
});
js/PersonController.js:
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {
$scope.firstName = "testName";
$scope.lastName = "";
$scope.age = 20;
$scope.isMajor = function()
{
return $scope.age > 18;
};
$scope.add = function()
{
registry.add({ 'firstName': $scope.firstName,
'lastName': $scope.lastName,
'age': $scope.age});
};
$scope.fullName = function()
{
return $scope.firstName + " " + $scope.lastName;
};
}]);
The binding does not occur: when i change the name or the age nothing happens, moreover in the beginning the input are all blank but i expect to see 20 in age and testName in firstName. The browser's console shows no error. Am i missing something?
Constraints: the service 'RegistryService' MUST be in another file.
Question:
with these two lines
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController',['registry', function($scope, registry) {
i am telling that the module named Person needs something called RegistryService to work, the controller PersonController will use the 'registry' thing located into the RegistryService (hence if i put here something that is not defined into RegistryService is an error). function($scope, registry) is the constructor of the controller that uses a global variable $scope and the variable registry taken from 'RegistryService'. Is my overall understanding of the dependency injection good?

You need to describe $scope injection too, since you expect it to be available in your controller function as the first parameter:
var app = angular.module('Person', ['RegistryService']);
app.controller('PersonController', ['$scope', 'registry', function($scope, registry) { }]);

You didn't inject $scope properly
app.controller('PersonController',['$scope', 'registry', function($scope, registry) {

Related

Angular1 sibling Controllers how can access each others data

I am trying to get FirstCtrl data in SecondCtrl, but there is no response in SecondCtrl, Please help me to solve this
I Have tried to use $broadcast and $emit on $rootscope. but there is not data coming on $on
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('FirstCtrl', function( $scope, $rootScope) {
$scope.firstName = 'Ganpat';
//$rootScope.$emit('firstName', $scope.firstName);
$rootScope.$broadcast('firstName:broadcast', $scope.firstName);
});
myApp.controller('SecondCtrl', function( $scope, $rootScope){
$rootScope.$on('firstName:broadcast', function(event,data){
$scope.firstName = data;
console.log(data);
});
});
</script>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstName}}
</div>
</div>
</body>
</html>
Code now compiles and runs properly. You can cut and past this into fiddler and run.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('UserService', function () {
var self = this;
var firstName = '';
self.SetFirstName = function (name) { firstName = name; }
self.GetFirstName = function () { return firstName; }
return self;
});
myApp.controller('FirstCtrl', ['$scope', 'UserService', function ($scope, UserService) {
UserService.SetFirstName("coolMan");
}]);
myApp.controller('SecondCtrl', ['$scope', 'UserService', function ($scope, UserService) {
$scope.firstNameTest = '';
$scope.service = UserService;
$scope.$watch('service.GetFirstName()', function (newVal) {
console.log("New Data", newVal)
$scope.firstNameTest = newVal;
});
}]);
</script>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>
Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstNameTest}}
</div>
</div>
</body>
</html>
EDIT
Addressing OPS comment.
I know this method will work and it will give a correct result, but i
have studied the $rootscope and event $emiter and $broadcast will do
this trick, so if you know about that then please tell me, thank you
for your answer.
What you want to do is a bad idea. Your method forces a tighter coupling between controllers. By working on the rootscope you are forcing all controllers to rely on a certain Item being in rootscope. This is bad because controllers are not self contained modules.
By passing around a service you can decouple the controllers. Meaning that they can be used as view controllers, directive controllers, pretty much anything that requires an isolated module.
Also using a service you can now cache the result, perform centralized business logic on it, and encapsulate how you get the data. This cannot be done easily on the rootscope.
To sum it up, I will not show you a terrible way of doing what you want done. It is not good and will let other people whom look at this post use bad practices.

Why will always use anonymous function in AngularJS

I see almost tutorial use anonymous function in AngularJS, instead of normal function, like function name(para1) {}. Please see this link: http://www.w3schools.com/angular/tryit.asp?filename=try_ng_controller_property
I change to normal function, but it cannot work, Please advise. Thanks.
<div ng-app="myApp" ng-controller="personCtrl as main">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{main.fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
function fullName() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
The idea of $scope is to have an object where all fields and functions are defined on, so that you are able to reference the fields and functions from your template.
When you don't attach the function to $scope it will not be visible for angular to be called. So the contract is that in your controller function, you add everything you need to the $scope object passed by the framework and by doing so, you can later access the fields or call the functions from your template. Everything you reference in directives like ng-model or put into {{ }} will be evaluated by angular, but angular doesn't know what you mean with the expression fullName() as written in your snippet link or fails finding it in the controller when written as main.fullName().
For details on the concept of $scope have a look at the angular docs on scopes.
What you can do (and it is also a good practice) is to declare your function and then (maybe in tha init of the controlelr) assign them to the $scope ..so is more clear when you'll re read it something like:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = fullName; //<-- here you assign it
function fullName() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</body>
</html>

Unable to update Child controllers scope valriable

Im new to angular js and im not able to figure out how to change the child controller scope variable from parent controller. Here is the code snippet for that:
var mainApp = angular.module("mainApp", []);
var parentCtrl = function($rootScope, $scope, shareService, $log){
shareService.setDetails($scope.pdetails);
}
var mainCtrl1 = function($rootScope, $scope, shareService, $log){
$scope.msg = "Controller 1";
$scope.details = shareService.details;//shareService.details;
}
var mainCtrl2 = function($rootScope, $scope, shareService){
$scope.msg = "Controller 2";
$scope.details = shareService.details;//shareService.details;
}
parentCtrl.$inject = ["$rootScope", "$scope", "shareService", "$log"];
mainCtrl1.$inject = ["$rootScope", "$scope", "shareService", "$log"];
mainCtrl2.$inject = ["$rootScope", "$scope", "shareService", "$log"];
mainApp.controller("parentController", parentCtrl)
.controller("mainController1", mainCtrl1)
.controller("mainController2", mainCtrl2)
.factory("shareService", function(){
var shareData = {
details : "sadfgs detaisdfadsfasdf..",
setDetails: function(value){
this.details = value;
}
};
return shareData;
});
<html>
<head>
<title>Angular JS Views</title>
<script src='lib/angular.js'></script>
<script src='js/mainApp.js'></script>
<script src='js/studentController.js'></script>
</head>
<body ng-app = 'mainApp' ng-controller='parentController' ng-strict-di>
<div ng-controller='mainController1'>
1. Msg : {{msg}}<br/>
Share Details: {{details}}<br/><br/>
</div>
<div ng-controller='mainController2'>
2. Msg : {{msg}}<br/>
Share Details: {{details}}<br/><br/>
</div>
<input type='text' ng-model='pdetails'/>
</body>
</html>
Here is the Plunker link:
https://plnkr.co/edit/hJypukqMmdHSEZMVnkDO?p=preview
In order to change value of child controller from parent controller you can use $broadcast on $scope.
syntax
$scope.$broadcast(event,data);
$broadcast is used to trigger an event(with data) to the child scope from current scope.
In child controller use $on to receive the event(with data).
Here id the code snippet:
app.controller("parentCtrl",function($scope){
$scope.OnClick=function()
{
$scope.$broadcast("senddownward",$scope.messege);
}
});
app.controller("childCtrl",function($scope){
$scope.$on("senddownward",function(event,data)
{
$scope.messege=data;
});
});
In this example I am broadcasting the event on ng-click,you can use some other custom event.like $watch on $scope.
See this example
https://plnkr.co/edit/efZ9wYS2pukE0v4JsNCC?p=preview
P.S. you can change the name of event from senddownward to whatever you want
You can access the parent's scope properties directly due to the scope inheritance:
<div ng-controller='mainController1'>
Share Details: {{pdetails}}
</div>
Your example does not work because the controllers get executed only once before the view is rendered, pdetails is empty at that moment.
To monitor the changes to pdetails, you can use $watch in the child controller:
$scope.$watch('pdetails', function(newVal) {
$scope.details = newVal;
});

Execise angularJS windows alert not woring

i've a simple problem, i've copied and pasted some code and i'd like to show an alert with a value inside it. I'm just learning angular and the fuction works (i've places a console log inside it and it is executed), but the window.alert doesn't appear.
I've read this tutorial and tried changing the name of variable but it's still not working. In the online tutorial of angual everything is going fine so where is my mistake?
Here is the page code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<script type="text/javascript" charset="utf-8" src="greetings.js"></script>
</head>
<body>
<h1>Greetings</h1>
<div ng-app="greetings" ng-controller="GreetingsController as greeting">
<b>Greetings:</b>
<div>
Name: <input type="text" min="0" ng-model="greeting.name" required >
</div>
<div>
FamilyName: <input type="text" ng-model="greeting.familyName" required >
<select
data-ng-options="c for c in greeting.tipi" data-ng-model="greeting.selectedOption">
<!--<option ng-repeat="c in greeting.tipi">{{c}}</option>-->
</select>
</div>
<div>
<b>Greeting:</b>
<span>
{{greeting.total(greeting.selectedOption)}} {{greeting.name}} {{greeting.familyName}}
<button class="btn" ng-click="invoice.greet(greeting.selectedOption)">Greet</button>
<br/>
</span>
</div>
</div>
</body>
</html>
Here is the controller code greetings.js:
angular.module('greetings', [])
.controller('GreetingsController', function() {
this.name = "Name";
this.familyName = "FamilyName";
this.tipi = ["Hello", "Good Morning", "Good Afternoon", "Good evening"];
this.selectedOption = this.tipi[0];
this.total = function total(outGree) {
console.log(outGree);
return outGree;
};
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
});
To use an Angular service, you add it as a dependency for the component (controller, service, filter or directive) that depends on the service.
And $window is a service.
you should add the parameter or the dependency $window to use this service.
angular.module('greetings', [])
.controller('GreetingsController', ['$window', function($window) {
this.name = "Name";
this.familyName = "FamilyName";
this.tipi = ["Hello", "Good Morning", "Good Afternoon", "Good evening"];
this.selectedOption = this.tipi[0];
this.total = function total(outGree) {
console.log(outGree);
return outGree;
};
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
}]);
You need to include $window in your dependencies, or else your controller reads it as undefined.
Try the following:
angular.module('greetings', [])
.controller('GreetingsController', function($window) {
//Rest of your code
this.greet = function greet(outGree) {
console.log(outGree);
$window.alert(outGree);
};
});
I added $window as a parameter to the function of your controller.
the problem was in the html code:
<button class="btn" ng-click="invoice.greet(greeting.selectedOption)">Greet</button>
should have been:
<button class="btn" ng-click="greeting.greet(greeting.selectedOption)">Greet</button>

How to pass the variables to AngularJs config

I work with AngularJS Google Maps and need to configure the api_key in the module config part (question similar to this one).
My question is about configuring AngularJs modules
This is my test pen:
var app = angular.module('myapp', [])
/*
// HERE ?????
// I try to pass a value from the HTML (server side)
.config(function($window){
console.log($window.memKey);
})
*/
.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
$scope.name = $window.memName;
$scope.city = $window.memCity;
$scope.getMember = function(id) {
console.log(id);
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
var memKey = 'bb7de28f-0f89-4f14-8575-d494203acec7';
var memName = 'John';
var memCity = 'New-York';
</script>
<div ng-app="myapp" ng-controller="MainCtrl">
Member name: {{name}} <br>
Member city: {{city}}
</div>
How is possible to recuperate the memKey value from the HTML (Server) side?
your memKey is in an accesible scope, according on how you've declared it.
just do
app.config(function(){
console.log(memKey);
})
See snippet
You can access an existing angular module if you don't use the injection array. After you have the reference, you can declare constants eg:
<script type="text/javascript">
var app = angular.module('myapp');
app.constant('memKey', 'bb7de28f-0f89-4f14-8575-d494203acec7');
app.constant('memName', 'John');
app.constant('memCity', 'New-York');
//Or do them as one config object
</script>
--
.config(['memKey', 'memName','memCity' function(memKey, memName, memCity) {
}]);

Categories

Resources