Pass angular value to common JavaScript - 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.

Related

Angular not binding data on html directly

I'm a beginner in Angular (ver 1.6.3) and i ran into this problem:
i have a controller called prof:
(function () {
'use strict';
angular
.module('app.prof', [])
.controller('ProfController', ProfController);
/** #ngInject */
function ProfController($scope, Data)
{
var vm = this;
vm.documents = Data.documents;
vm.classes = Data.classes;
}
})();
Here's its associated module :
(function () {
'use strict';
angular
.module('app.prof')
.config(config);
/** #ngInject */
function config($stateProvider, $translatePartialLoaderProvider, msApiProvider) {
// State
$stateProvider
.state('app.prof', {
url : '/prof',
views : {
'content#app': {
templateUrl: 'app/main/prof/prof.html',
controller : 'ProfController as vm'
}
},
resolve : {
Data : function(msApi){
return msApi.resolve('data#get');
}
}
});
$translatePartialLoaderProvider.addPart('app/main/prof');
msApiProvider.register('data', ['app/data/prof/prof-data.json']);
}
})();
And here's the main problem : i have this html :
<div class="document" ng-repeat="document in vm.documents">
<ms-card template="'app/custom-directives/prof-card/prof-card.html'"
ng-model="document"></ms-card>
</div>
it works perfectly fine, the data is correctly binded and all, but when i put the template called directly in the page instead of calling it throught a <ms-card> it doesn't work anymore !
i've tried to put some console.log() a little eveywhere but it always says the data isn't defined; i don't get it.
Plus, the ng-repeat always works fine
Edit : a bit of the html i call :
<md-list-item class="document-item md-white-bg md-2-line" md-ink-ripple>
<div class="media ml-16">
<img class="image-apercu" ng-src="{{card.media.image.src}}" alt="{{card.media.image.alt}}" ng-show="card.media.image">
</div>
ps : when i add the html directly i don't forget to put the ng-model="document" but it still doesn't work
This is very confusing for me :/
You cannot bind the "vm" object with "$scope". you need to bind it with Scope like
function ProfController($scope, Data)
{
//$scope.vm = this;
$scope.vm.documents = Data.documents;
$scope.vm.classes = Data.classes;
}
Your Html Should be like :
<body ng-app="app.prof" ng-controller="ProfController">
<div class="document" ng-repeat="document in vm.documents">
<ms-card template="'app/custom-directives/prof-card/prof-card.html'"
ng-bind="document"></ms-card>
</div>
</body>
Hope this will work for you
In the end i found myself - I put the controller back like it was, i renamed all the {{card.something}} as {{document.something}} and i removed the ng-bind="" in the <div> that was being looped.

angularjs $scope.InputModelName is undefined

I have one input field and trying to get the value from this.
<!DOCTYPE html>
<html ng-app="Application">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script>
var app = angular.module('Application', []);
app.controller('ApplicationRootController', function ($scope) {
console.log("[Controller level value - which never come out] $scope.antiForgeryToken_test = " + $scope.antiForgeryToken_test);
$scope.SubmitFunction = function(){
console.log("[Value - which come out only after form submitted] $scope.antiForgeryToken_test = " + $scope.antiForgeryToken_test);
};
});
</script>
</head>
<body>
<form id="ApplicationRoot"
ng-controller="ApplicationRootController"
ng-submit="SubmitFunction()" >
<button type="submit">Submit</button>
<div id="AntiForgeryKeyHolder">
<input
id="antiForgeryToken_test"
ng-model="antiForgeryToken_test"
ng-init="antiForgeryToken_test='PassKey123456789'"
type="hidden" />
</div>
</form>
</body>
</html>
But what I got is undefined, So I tried using form submitting, then value come out. So my question is
How to get value from this simple input field without submitting form?
Plunker
Updated
Why console.log give me undefined since the same code give me value when it was called by submitting form ?
Code placed in view, executed after code placed in js controller. So when controller execute and call line
console.log("[Controller level value - which never come out] $scope.antiForgeryToken_test = " + $scope.antiForgeryToken_test);
ng-init in view yet not work.
For solve this you can use setTimeout like
setTimeout(function(){
console.log("[Controller level value - which never come out] $scope.antiForgeryToken_test = " + $scope.antiForgeryToken_test);
});
here callback execute after delay, so it can be after ng-init
updated plunker
Wait till controller scope receives the ng-init data from UI.
var app = angular.module('Application', []);
app.controller('ApplicationRootController', function ($scope, $timeout) {
$timeout(function(){console.log($scope.antiForgeryToken_test);}, 2000);
});
After I got great knowledge from #Grundy code in view - called after code inside controller
So, I was trying to fire code from controller only when the content is fully loaded. My final solution is below
angular.element(document).ready(function () {
console.log("[Value - After form loaded completly] $scope.antiForgeryToken_test = " + $scope.antiForgeryToken_test);
});
Plunker

Backbone can't see a key passed to the template [duplicate]

This question already has answers here:
Underscore template throwing variable not defined error
(2 answers)
Closed 7 years ago.
I have a very simple code in order to use a backbone/underscore template.
HTML:
<script type="text/template" id="search_template">
<div>Name comes here: <h4><%=name%></h4></div>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"></div>
JS:
$(function(){
var SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
var tmpl = $('#search_template').html(),
compiled = _.template(tmpl, { name:'hello' });
$(this.el).html(compiled);
}
});
var search_view = new SearchView({ el: "#search_container" });
});
The problem is it can't see the key "name" which should be passed into template. I still don't figure out why.
The whole code sample is located here: http://plnkr.co/edit/7fV2azTh6cpjmUxIBHvJ?p=preview
You are not using Underscore's template method correctly.
The compilation step is not where you pass in your parameters to be replaced by the template. Rather, the compilation step produces a function. The result of invoking the compiled function, with your view model parameters as the first argument, will return a string of your template with the replaced values of your view model.
render: function () {
var tmpl = $('#search_template').html(),
compiled = _.template(tmpl);
this.$el.html(compiled({ name:'hello' }));
}
An additional point: Notice how a Backbone View already gives us a convenient this.$el, so we don't need to do the $(this.el) step again.
change
compiled = _.template(tmpl, { name:'hello' });
to
compiled = _.template(tmpl)({ name:'hello' });
_.template returns function that accepts data to be inserted into template
http://plnkr.co/edit/GqFBvepfukIwDGLQa8Ki?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>

Passing data from Angular service to controller and refreshing view

So I have a bootstrap list:
<div class="ajax_company_list" ng-app="app">
<div class='list-group' ng-controller="PolicyController as policyCtrl">
<a href="#" class='list-group-item' ng-repeat="company in policyCtrl.companies">{{company.primary_name}}
</a>
<div id="loadingIcon" class='list-group-item'>
Loading...
</div>
</div>
</div>
Here is my Angular Javascript:
var app = angular.module('app', []);
app.controller('PolicyController', ['$scope', 'CompanyService', function($scope, CompanyService) {
$scope.companies = [
{
policy_number: 12345,
primary_name: "test"
}
];
$scope.getCompanies = function() {
CompanyService.fetchCompanies()
.success(function(data) {
$scope.companies = data.companies;
})
}
}]);
app.factory('CompanyService', ['$http', function($http) {
return {
fetchCompanies: function() {
return $http.get('http://spoonerinc:8886//json/glmod_Spooner-Inc?pagenum=1');
}
}
}]);
I basically have 2 questions. If I set $scope.companies equal to an array of objects, it does not show up but if I change $scope.companies to this.companies, it starts working again. Why is this?
2nd question, I can see the service call running in my net tab and can console.log the data and it reads fine. But it is not updating my actual list at all and I'm not sure what I'm doing wrong.
I am fairly new to Angular so if there is any advice on how I can do my code better, please let me know.
Thanks!
Because you are using the "Controller As" syntax, which effectively publishes the entire controller object to the scope.
What happens under the hood looks something like this:
function myCtrl($scope){
$scope['someAlias'] = this;
}
If you are going to use the controller as syntax, it's best to use a more object based approach instead of pushing things onto the $scope
Either on the prototype:
function myCtrl(companiesService){
this.companiesService = companiesService;
this.init();
}
myCtrl.prototype = {
init:function(){
var _this = this;
_this.companiesService.get()
.then(function(result){
_this.companies = result.data;
});
}
};
Or as closure style object:
function myCtrl(comapniesService){
var ctrl = {};
function init(){
companiesService.get()
.then(function(result){
ctrl.companies = result.data;
});
}
return ctrl;
}
For your second question, I think your problem is here:
ng-repeat="company in policyCtrl.companies"
You don't need to specify the controller as a prefix, since you've already declared it with ng-controller. It should be:
ng-repeat="company in companies"
And ng-controller to be:
ng-controller="PolicyController"
My guess is that the first problem will go away once you correct this.

Categories

Resources