How to pass scope variables from my controller to javascript - 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>

Related

Read and edit global javascript variable from Angular

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?

AngularJS variable accessible from the whole code

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

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

Pass angular value to common JavaScript

I am trying to pass a value from angular scope to common JavaScript.
The JavaScript is like this
<script type="text/javascript">
var epaycode = null;
var epaybuysum = null;
paymentwindow = new PaymentWindow({
'merchantnumber': epaycode,
'amount': epaybuysum,
'currency': "DKK",
'windowstate': "4",
'paymentcollection': "1",
'iframeheight': "250",
'iframewidth': "500"
});
paymentwindow.append('payment-div');
setTimeout(function(){
paymentwindow.open();
}, 1000);
The angular controller code is like this
$scope.showpay = function () {
$window.epaybuysum = $scope.buysum * 100;
$window.epaycode = $scope.ePayCode;
};
The Angular showpay() function is called after the common JavaScript is initialized. The buysum and ePayCode is set earlier in the program. They have value and is tested with console.log().
Why doesn't the epaybuysum and epaycode getting transferred to the common JavaScript?
Is there any other solutions to passing values to common JavaScript from Angular controllers?
Have a look at this plunker: http://plnkr.co/edit/lQiXpObbWuG84CNbcZt2?p=preview
<div ng-controller="MainCtrl">
<input ng-model="buyCode">
<input ng-model="buySum">
<p>{{buyCode}} ... {{buySum}}</p>
<button ng-click="showPay()">call showPay</button>
</div>
<button onclick="buttonClick()">Console.log</button>
The first button calls your showPay function(the one on scope). The second button calls console.log (outside the angular controller, simple js). For this simple usecase it seems to work as expected. How are you calling showPay function?
Try this:
(function (angular, epaycode) {
'use strict';
var module = angular.module('abc', []);
//Your controller etc.
}
})(angular, epaycode);
Updated
The plunker in the comments section shows how you can do this.

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