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
Related
I'm trying to use AngularJS in my cfm files to display data from cfquery resultset.
I used below code in my cfm file.I'm not able to see any output.
P.S. I'm really new to AngularJS. So if anyone can please help me out here it would be great.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html ng-app="Demo">
<head>
<link rel="stylesheet" href="/Applications/_Common/style.css" type="text/css">
</head>
<body>
<cfsetting enablecfoutputonly="Yes">
<CF_GetProjectData project_number=349246 query_name="GetProject">
<div ng-controller="DemoController">
<div ng-repeat="number in project">
{{number.project_number}} - {{number.project_name}}
</div>
<!-- <input name="imprint" type="text" size="10" ng-model="first">
<p>{{first}}</p> -->
</div>
<cfoutput>
<script language="JavaScript" src="/CFIDE/scripts/wddx.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script language="text/javascript">
var theProjectArray; < cfwddx action = "CFML2JS"
input = "#GetProject#"
toplevelvariable = "theProjectArray" >
</script>
<script>
var Demo = angular.module("Demo", []);
Demo.controller("DemoController", function($scope) {
$scope.project = theProjectArray;
alert(theProjectArray);
});
</script>
</cfoutput>
<cfsetting enablecfoutputonly="No">
</body>
</html>
I am not sure about Angular.js but based on the code you have posted, it seems, you need to wrap ng-controller div in cfoutput. This is because you have set enablecfoutputonly="Yes". So only the content inside cfoutput will be rendered.
I'm a CF developer that's currently learning Angular as well. First of all Angular is a MVC framework and will work for you best of you follow the rules of Separation of Concern (SoC). I know unless you are using Object Relational Mapping (ORM) in CF this is counter intuitive but it will save you so much hassle and trouble shooting later.
For your problem right now though i would
combine both script blocks.
your variable theProjectArray is defined with var so it's not
global. Are you sure it's making it into your controller?
the line toplevelvariable = "theProjectArray" > ... is the greater
than sign a type-o?
After you've done those i would console.log(theProjectArray); right after it's defined. Then console.log(theProjectArray); again in your controller to ensure it's getting passed in properly.
Just for your reference here is a very basic example of a controller and a factory in angular calling a CFC. Since i've been doing things this way the only time i use ColdFusion is to retrieve data and model it. It's simplified my code and logic quite a bit and has allowed me to do a lot more now that i'm not leaning on ColdFusion.
var myapp = angular.module("test.myapp", [])
myapp.controller("MyController", function($scope, getevent) {
$scope.myData = {};
$scope.myData.doUpdate = function(item, event) {
getevent.GetProgram(item).success(function(data, status, headers, config) {
console.log(data.DATA);
$scope.test = data.DATA;
$scope.test.DATE = new Date(data.DATA.DATESTART);
});
getevent.GetProgram(item).error(function(data, status, headers, config) {
console.log("FAILED: "+item);
alert("AJAX failed!");
});
}
});
myapp.factory('getevent', function($http){
return {
GetProgram: function(item) {
var programInfo = '/foundation/cfc/calendar.cfc?method=getevent&eventid='+item;
return $http.get(programInfo);
}
};
});
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.
I have to call the submit() function the moment the page loads. However this sort of arrangement gives a submit() method not found error. I am unable to understand the placement of ng-controller and onload.
Also if there is any alternative way of doing this with angular, please point that out as well.
PS: This is a code snippet. All variables have been defined.
<body ng-controller="DashboardDisplay" onload="submit()">
<div class="container-fluid" >
{{scope.arr}}
</div>
</body>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('DashboardDisplay', ['$scope','$http',function($scope,$http) {
$scope.submit = function(){
var jsonOb = {"A":"B"};
$http.post(URL,jsonOb).
success(function(response) {
console.log('got it' + response);
$scope.arr=response;
}).
error(function(data, status, headers, config) {
console.log('nufin' + status);
});
}
}]);
Use ng-init instead of onload i.e
<body ng-controller="DashboardDisplay" ng-init="submit()">
And removed scope which before arr in html i.e
{{scope.arr}} to {{arr}}
I have created working DEMO
https://jsfiddle.net/Shital_D/x2k8n23n/1/
I have a cordova app in which I want to show the details of a location. For some reason when I try to display a variable in HTMl which is being successfully assigned in JS, nothing appears.
JS controller:
app.controller('placeCtrl', function($scope, LocDat){
LocDat.async().then(function(d){
$scope.item= places.selectedItem;
$scope.locs = [];
for(var i=0; i<d.length; i++){
if(d[i].attributes.Joint.id === places.selectedItem.id){
getDistance(d[i]);
$scope.locs.push(d[i]);
}
}
$scope.showSite = function(){
//var ref = navigator.app.loadUrl($scope.item.attributes.Website, '_blank');
var ref = window.open($scope.item.attributes.Website,'_blank','location=yes');
}
$scope.showDetail = function(index){
var selectedItem = d[index];
d.selectedItem = selectedItem
$scope.l = selectedItem;
console.log($scope.l.attributes.City);
$scope.ons.navigator.pushPage('location_detail.html', { title : d.selectedItem.attributes.Address });
}
});
HTML:
<!DOCTYPE html>
<html>
<body>
<div ng-controller="placeCtrl">
<ons-page class="center" ng-device-backbutton="myNavigator.popPage()">
<ons-toolbar>
<div class="left"><ons-back-button ons-if-platform="ios">Back</ons-back-button></div>
<div id="title" class="center">{{l.attributes.City}}, {{l.attributes.State}}</div>
<!--<div class="left" onclick=".myNavigator.popPage()"><ons-back-button>Back</ons-back-button></div>-->
<!--<div class="center">Page 2</div>-->
</ons-toolbar>
<h2 align="center">Location Details Go Here</h2>
<!--enter more content here-->
</ons-page>
</div>
</body>
</html>
Image of the Console output:
Apparently my reputation is too low to post images... Seriously? Anyway, it displays the City name in the console successfully, but the html only shows the comma
Services that make async calls, such as your LocDat, do not automagically trigger a digest event when they return. If you're writing a service it should call a $scope.$apply() chained to the end of the promise. Alternatively you can wrap any changes to $scope variables in an apply and that should get you where you need.
$scope.$apply( function() { $scope.l = selectedItem; } );
In angularjs data binding, if the data type is list or object, it will pass by reference value in view.
When you do like $scope.l = selectedItem, the reference is changed, but the watched reference is previous one. So it will be always better to bind by an attribute on an object, but not the object itself. like:
<div id="title" class="center">{{obj.l.attributes.City}}, {{obj.l.attributes.State}}</div>
And update in controller with:
$scope.obj.l = selectedItem;
The issue was that the scope changed when I loaded the new page. I'm now passing the data through the parameters of onsenui's pushpage function and assigning them to the scope variables in a separate controller.
I have a controller with such:
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
If next() (with ngClick) is called 3 times, we get:
//1
//2
//3
but if back() (with ngSwipeLeft) is called it returns
//-1
when I'm obviously expecting
//2
What am I missing here?
update: including ngTouch details - this seems to be the problem.. ngTouch is included.
When I watch the myVar value - its like it exists twice - one with the ngSwipeLeft call, and one with the ngClick call
Your snippet looks fine to me. You need to provide more code, error might be somewhere else. Look at the code below.
<!doctype html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-touch.min.js"></script>
<script>
var app = angular.module('myapp',['ngTouch']);
var controller = app.controller('mycontroller', ['$scope',function($scope){
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}]);
</script>
</head>
<body ng-controller="mycontroller">
<div>
<h1>MyVar: {{myVar}}!</h1>
<input type="button" value="back" ng-click="back()"/>
<input type="button" value="next" ng-click="next()"/>
</div>
</body>
</html>
Ok, so I've figured out my problem - I wasn't providing enough detail in the question - but if someone runs into something similar in the future, heres what was going on:
I was declaring my controller with ng-controller="myCtrl" in the templates, but also using routing, where I declared my controller like:
$routeProvider.when('/', {
templateUrl: 'myUrl.html',
controller: 'myCtrl'
});
This was instantiating the controller twice, and obviously causing problems (although that seemed to the only one to surface for now).
Removing the controller definition from the routing or the view did the trick.
need to see your html not sure about your problem, here is a sample working code,
<div ng-app="myapp">
<div ng-controller="IncDecController">
<span>current value is {{myVar}}</span>
<img src="https://angularjs.org/img/AngularJS-large.png" ng-swipe-left="back()"></img>
<button ng-click="next()">next</button>
</div>
</div>
script:
angular.module('myapp', ['ngTouch'])
.controller('IncDecController', ['$scope', function ($scope) {
$scope.myVar = 0;
$scope.back = function () {
$scope.myVar--;
};
$scope.next = function () {
$scope.myVar++;
};
}])