Read and edit global javascript variable from Angular - javascript

I have an angular app where in my index.html i have a variable inside a tag, like this:
<script type="text/javascript">
let global = 5;
</script>
I need to read and edit the value of this variable, inside an angular component, but I do not know how to do it.
I saw that it is possible to read the value if you create the variable inside the "window" object of javascript (window.global = 5) and then use it in angular component, but i think it would not work for me because i need that variable to be outside, as specified above.
Is it possible? Any ideas?

The keyword declare to the rescue: first, declare your global with var (let doesn't work)
<script type="text/javascript">
var someVar = 5;
</script>
and access it in, say, Angular component:
declare var someVar;
// ...
this.foo = someVar;
https://stackblitz.com/edit/angular-ivy-zjpnzq?file=src%2Fapp%2Fhello.component.ts

Finally I used an aproximation of #robin-zigmond answer. I changed let to var in the script tag and in my angular component I access the variable using:
window["global"]
I can edit the value inside a component using, for example:
window["global"] = 6
Moreover, I tried #mbojko answer and it worked too.

You can pass the window varaible to the scope in your controller.
<!DOCTYPE html>
<html>
<script>window.HELLO_MSG = 'Hello,';</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ wlcmMsg + " " + firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.wlcmMsg = window.HELLO_MSG;
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Or you can inject the whole window object like here:
How to inject window into a service?

Related

Angular.js output value live on ng-click

I'm new to angular and little bit confused with it. So basically I created a simple button and i want to run function foo() whitch assigns variable var one = 1; to $scope and outputs it in <p>{{one}}<p> every time its clicked like in live typing but this seems not working. Please provide me a solution to this.
<html ng-app="app">
<!-- Body tag augmented with ngController directive -->
<body ng-controller="myController">
<input type="text" ng-model="name">
<p>{{name}}</p>
<p>{{one}}</p>
<button ng-click="foo()">1</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="controller.js"></script>
</body>
</html>
controller:
var app = angular.module('app',[]);
app.controller('myController', ['$scope',function($scope){
var one = 1;
$scope.name = name;
function foo(){
return $scope.one = one;
}
}]);
function foo() dont exist in $scope your controller "myController"
if you declaration:
$scope.foo = function(){}
in your controller, then this work for you
when you are calling controller function from the html, controller function should be scope. Other wise ng-click directive doesn't recognize the function.
same concept goes to binding variable to html. only scope variables can directly bind to html using curly brackets. so inside foo function var one should assign to scope.one in order to display it in the html.
angular.module("app",[])
.controller("ctrl",function($scope){
var one = 1;
$scope.name = name;
$scope.foo = function(){
$scope.one = one;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="name">
<p>{{name}}</p>
<p>{{one}}</p>
<button ng-click="foo()">1</button>
</div>

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>

initialize javascript variable with angularjs scope variable

How to initialize javascript variable with the value of AngularJS scope variable...
Something like:
xyz.controller(
(
$scope.country="Canada"; );
javascript :
<script>
var country = {{scope.country}};
</script>
You can access the angular js scope variables by using $scope.scopeVariableName
In order to assign this to a javascript variable just by
var varibleName = $scope.scopeVariableName;
if you are using scope objects(using controllerAs syntax) in UI, we can assign this using this variable
var varibleName = this.scopeVariableName;
Example:
<div ng-controller="yourController">
{{scopeVariableName}}
</div>
controller :
function yourControllerFunction($scope){
$scope.scopeVariableName = "Canada";
var variableName = $scope.scopeVariableName;
}
yourControllerFunction.$inject = ['$scope'];
angular.module('yourMainModule').controller('yourController', yourControllerFunction);
HTML:
<body ng-controller="MainCtrl">
<p>{{country}}</p>
</body>
JS:
var xyz = angular.module('app', []);
xyz.controller('MainCtrl', function($scope) {
$scope.country = 'Canada';
var country = $scope.country;
jQuery('html, body').animate({scrollTop: 0}, 200);
});
Here is a Plunker https://plnkr.co/edit/hHRPzDQKbtSUppzpxfI2?p=preview

How to pass scope variables from my controller to javascript

Hi I have a controller variable
$scope.submitQuestion = function(){
$scope.post.createdTime = createdtime;
$scope.post.creator = $scope.user.profile.username;
$scope.post.creatorUID = $scope.user.uid;
$scope.post.creatorpic = $scope.user.profile.userpic;
$scope.post.postmedia = $scope.object.video.info.uuid;
$scope.post.postmediaimage = $scope.object.image.info.uuid;
Post.create($scope.post).then (function(ref) {
$location.path('/posts/' + ref.name());
});
};
And this is my view I am planning to use
<body>
<div id="player"></div>
<script>
var player = new Clappr.Player({source:
{{post.postmedia}} , parentId: "#player"});
</script>
</body>
Is it possible to pass my scope variable $scope.post.postmedia to the script tag ?
Yes there is another way to use $window service. Its equal to javascript's window object. You should assign a attribute to window object first and use this global variable value from anywhere in your multiple js files.
You should inject $window service first in your controller. Your controller declaration will look like
angular.controller('MyController', ['$scope', '$window', function ($scope, $window){
$window.post.postmedia = $scope.object.video.info.uuid; // Assign value first
}])
Now you can use this attribute value from everywhere. Like
<script>
var player = new Clappr.Player({source:
post.postmedia , parentId: "#player"}); //post.postmedia will work if it will have been assigned first else it will show undefined
</script>

my angular app does not work

I have this code:
<!doctype html>
<html ng-app="myApp" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function ($scope) {
$scope.count = 0;
$scope.increment = function (){
$scope.count = $scope.count + 1;
}
});
</script >
<div ng-controller="FirstCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
what is wrong with it?
When I work without controllers it's works fine but when I use app and app.controller It will not work. why is that? am I doing something wrong?
The "Controller as" syntax is only available from version 1.1.5+
By what i know when using "Controller as" and you want to reference a variable with the assigned controller alias (in your case "app1") then you should assing the variables with "this." syntax in the controller, or access the variables without the "app1", then it will try to get it from the scope.
http://jsbin.com/zehagogoku/3/edit
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function ($scope) {
this.count = 0;
this.increment = function (){
this.count = this.count + 1;
};
$scope.count = 0;
$scope.increment = function(){
$scope.count = $scope.count + 1;
};
});
You are mixing styles here. In your HTML, you are using the Controller As syntax, where you write FirstCtrl as app1. This makes an object called app1 on the scope, which is an instance of your FirstCtrl. app1.count, app1.increment(), etc. would be properties of the FirstCtrl object.
In your controller, you are not creating properties on the controller. You are, instead, assigning your variables as properties on the $scope object.
Using $scope has advantages, in that it is essentially a global object, so it is accessible from everywhere in your app. However, it's disadvantages are also rooted in the fact that it's a global object.
You can either change your javascript to match the Controller As syntax, as shown:
app.controller("FirstCtrl",function () {
//create an alias to this for consistent reference
var app1 = this;
app1.count = 0;
app1.increment = function (){
app1.count += 1;
};
});
Or, you can change your HTML to use $scope:
<div ng-controller="FirstCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
change in the javascript:
$scope.count += 1;
note, you don't have to reference $scope inside the HTML, as it's presence is implicit. However, this line in your javascript $scope.count = this.count + 1;
will never work in either case, again because you are mixing styles.
Also, as mentioned, Controller As syntax requires Angular 1.1.5 or higher.

Categories

Resources