AngularJS variable accessible from the whole code - javascript

as you can see I have opened .xml file and parsed it to a xmlDoc. What I am trying to achieve is that this xmlDoc will be accessible from the whole script(I want to make some functions later which will be displaying elements from .xml to a screen). I searched the web and find that it is possible via global variable $rootScope but couldn't implement it correctly. I hope you guys can help me. Thanks.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<p id="title">asd</p>
<button name="opt1" ng-click="">YES</button>
<button name="opt2" ng-click="">NO</button>
<script>
var app = angular.module('myApp', []);
var parser, xmlDoc;
app.run(function($rootScope, $http) {
text = $http.get("file.xml").then(function(response) {
return response.data;
}).then(function(text) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("title").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
});
});
</script>
</body>
</html>

There are many ways in angular to declare and use a global variable.
examples:
1. By using $rootScope.
we need to add a dependency in our controller or service like:
app.controller('myCtrl', ['$rootScope', '$scope', function($rootScope, $scope){
$rootScope.yourVar = 'YourValue';
....
....
}]);
and then You can use this `yourVar` variable anywhere in your code.
Another way is by using angular factory or servive.
app.factory('factoryObj', ['$scope', function($scope){
let factoryObj.yourVar = 'yourValue';
return factoryObj;
}]);
Now in any controller or any other service, by using this factoryObj as a dependency and then inside that controller or service we can use factoryObj.yourVar as a variable. as:
app.controller('myCtrl',['$rootScope','$scope','factoryObj'function($rootScope,$scope, factoryObj){
console.log('factoryObj.yourVar value: ',factoryObj.yourVar);
}]);

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.

How To pass data from angularjs to javascript

How to pass data from angularjs to javascript
<input type="hidden" ng-model="data.value" id="MyData">
<script>
var MyData = GetEelementById(MyData).value;
</script>
i cant make it work .. , what is the correct way ?
The above piece of code is just part of VIEW only.
You need to go through basic tutorials of AngularJs and understand how views and controllers work.
To be specific, You can access the data (you expecting) in the controller of the view.
Like:
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="data.value" id="MyData">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data={
value:"Deepak"
}
});
</script>
Edit as per the discussion in comments on answer
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data={
value:"Deepak"
}
// $scope.data.value is the initial value for the model and view is rendered with this value intially.
//You can also change this value with javascript to reflect in the view as well
//Your post request comes here
// **$scope.data.value reflects the updated Value of Input Box**
});
</script>

How to add multiple controller in single page in AngularJS

I am new to AngularJS I have a problem with this code. I want to add multiple controller in single ng-app. But it execute first one. Why not second one?
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angul /1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-controller="cont1">
<input type="text" ng-model="fullname">
{{fullname}}
</div>
<div ng-controller="cont2">
<input type="text" ng-model="fname">
{{fname}}
</div>
<script>
var app = angular.module("myapp", []);
app.controller('cont1', function ($scope) {
$scope.fullname = "";
});
var new = angular.module('myapp', []);
new.controller('cont2', function ($scope) {
$scope.fname = "";
});
</script>
</body>
</html>
Because you are overwriting the first myapp module when you do var new= angular.module('myapp',[]);.
Your code should be:
var app = angular.module("myapp", []);
app.controller('cont1', function($scope) {
$scope.fullname = "";
});
app.controller('cont2', function($scope) {
$scope.fname = "";
});
or
var app = angular.module("myapp", []);
app.controller('cont1', function($scope) {
$scope.fullname = "";
});
angular.module("myapp").controller('cont2', function($scope) {
$scope.fname = "";
});
The second parameter[] passed to module() makes the difference
To best way to define controllers, directives, factories etc... is
define your modules names in a separate file
app.module.js
angular.module("myapp",[]); // inside [] you define your module dependencies
for controllers create separate file (depending on your requirement even you can create 1 file for 1 controller)
some.controller.js
angular.module("myapp").controller('someCtrl'['$scope', function($scope){
}]);
angular.module("myapp").controller('someOtherCtrl'['$scope', function($scope){
}]);
NOTE:
Two types you can write controller
TYPE1 (not recomended)
.controller('ctrlName', function($scope){
});
TYPE2 (recomended)
.controller('ctrlName', ['$scope', function($scope){
}]);
Reason
So as you can see in the TYPE2 we are passing controller dependencies in an array, so when we compile our program angular will give the name as eg:a to $scope inside function() and treat it as $scope.
With the TYPE1 you need to follow specific order while defining controller dependency otherwise angular will through error because in this approach angular simply treats first dependency as $rootscope, second as $scope and so on....
For Eg:
you can't pass dependencies to your controller like this
.controller('ctrlName', function($http, $scope) {
});
this will throw error
if you define like
.controller('ctrlName', function($scope, $http) {
});
this will work fine since its in order that angular wants.
You can define multiple controllers in a single module in this way also:
angular.module("myapp",[]);
.controller('cont1',function($scope){
$scope.fullname="";
});
.controller('cont2',function($scope){
$scope.fname="";
});
When you are defining modules, don't use var. You can find some of the Angular best practices here: Angular Style Guide/Best Practices

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

Angularjs and web services

<div ng-app="myapp" ng-controller="hello">
<script>
function Hello($scope, $http) {
$http.get('http://rest-service.guides.spring.io/greeting').
success(function(data) {
$scope.greeting = data;
});
}
</script>
and I would like to print the content like this {{greeting.id}}.
the code snippet is going to get data in JSON format from "http://rest-service.guides.spring.io/greeting" using angularjs. This isn't working in eclipse. Any ideas to make it work ?
I'm fairly certain that the value of ng-controller is case sensitive.
So, this:
ng-controller="hello"
will look for a function with the name: hello, not Hello.
Here is a plunker demonstrating the issue.
Change your controller code like this.
(function () {
var myApp = angular.module('myModule');
myApp.controller('hello', ['$scope', '$http', function ($scope, $http) {
$http.get("http://rest-service.guides.spring.io/greeting").then(function(data){
$scope.greeting=data;
});
}]);
})();
and in the html
{{greeting.data.id}}
I checked it in plunker. It is working fine

Categories

Resources