Angular.JS binding isn't working - javascript

I have an extremely simple setup here
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body ng-app="locationApp" ng-controller="locationController">
<button ng-click="getLocation()">Get Location</button>
<br />
Latitude: {{city.Latitude}} <br />
Longitude {{city.Longitude}} <br />
<script src="Scripts/lib/angular.min.js"></script>
<script src="Scripts/app.js"></script>
</body>
</html>
app.js:
var locationApp = angular.module('locationApp', []);
var locationController = locationApp.controller("locationController", function ($scope, $http) {
$scope.getLocation = function () {
$http.get("https://localhost:44320/api/location?cityName=sg").then(function (location) {
$scope.city = location;
});
}
});
When I click on the Get Location button, my bindings {{city.Latitude}} and {{city.Longitude}} remains blank.
I tried debugging by setting a break point in Chrome, and my values do show up. So I'm not sure what I'm missing. Any help?
I'm using AngularJS 1.6

The parameter passed to the then function is the response object. The response object contains the data:
$http.get("https://localhost:44320/api/location?cityName=sg").then(function (response) {
$scope.city = response.data;
});

Is the location returned the response from the web service?
Did you actually want to do:
$scope.city = location.data;

You want the data object returned in the get function.
Try $scope.city = location.data

Use $scope.apply() after getting the response to start the new digest.

Related

AngularJS controller cannot store Youtube API response results to a variable

I'm trying to make a search request using youtube's API and store the result to a variable inside an AngularJS' controller.
This is my app.js file.
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', function($scope){
this.data = '###';
this.search = function(){
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'beatles'
});
request.execute(function(response){
var responseString = JSON.stringify(response, '', 2);
this.data = responseString;
// document.getElementById('response').innerHTML += this.data;
});
}
}]);
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad() {
gapi.client.setApiKey('blahblahblahblahblahblah');
}
and this is the index.html.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body ng-controller="myController as c">
<div ng-click="c.search()" class="btn btn-success">
Press me!
</div>
<h2>Result</h2>
<pre id="response"> {{c.data}} </pre>
</body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</html>
In the html code, there is a press me button which invokes the search() function which makes the request. The javascript console shows that the request was executed successfully.
I store the response result to a variable called data. The problem is that the content of the variable does not change. However, if I store this value inside the .innerHTML of a document element (the classic Javascript way), this works, and the results are shown successfully (this line is currently commented out).
Why response result cannot be stored in a variable that lives outside this function?
Please try like this.
app.controller('myController', ['$scope', function($scope){
var c = this;
c.search = function(){
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'beatles'
});
request.execute(function(response){
var responseString = JSON.stringify(response, '', 2);
c.data = responseString;
});
}
console.log(c.data);
}]);
I am assuming gapi.client is not an angular library. The request for search is concluded outside angularjs and hence angular doesn't update scope with new response. You will have to call the digest cycle in callback of request.execute. Something like the following should work:
request.execute(function(response){
var responseString = JSON.stringify(response, '', 2);
this.data = responseString;
$scope.$digest();
});
I hope this helps.
Finally, the solution to the problem was a combination of the two answers above:
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$q', function($scope, $q){
var c = this;
c.search = function(){
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'beatles'
});
request.execute(function(response){
var responseString = JSON.stringify(response, '', 2);
c.data = responseString;
$scope.$digest();
});
};
}]);
we first need to set the controller itself to a variable with
var c = this;
and then we need to call $scope.$digest() as well to update the c.data value. Now right at the time the button is pressed, the result is shown in the page.

ReferenceError: random is not defined at Scope.$scope.generateRandom angular js

For some reason it gives me the error:
ReferenceError: random is not defined at Scope.$scope.generateRandom
I dont know what im doing wrong, you can go check out the website im using to do this HERE.
index.html:
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset="UTF-8" />
<title>Basic Login Form</title>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src = "https://rawgit.com/nirus/Angular-Route-Injector/master/dist/routeInjector.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
<script type="text/javascript" src="script23.js"></script>
</head>
<body ng-app = "app" ng-controller = "app">
<button ng-click = "generateRandom()">Generate Random Number</button>
<br> {{randomNumber}}
</body>
</html>
script23.js:
var app = angular.module('app', []);
app.service('random', function(){
var randomNum = Math.floor(Math.random()*10)
this.generate = function(){
return randomNum;
}
});
app.controller('app' , function($scope){
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
})
To use service in controller, you need to inject it.
app.controller('app', function ($scope, random) {
I'd recommend you to use following syntax:
app.controller('app', ['$scope', 'random', function ($scope, random) {
See Why we Inject our dependencies two times in angularjs?
Change your controller like this, since you are using the service 'random'
myApp.controller('app', ['$scope','random', function( $scope,random)
{
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
}])
Here is the working Application

Why printing multiple times on calling a function - AngularJS

I am calling a function from the controller scope, but in the console the values are printed three times. Why is this happening?
SOURCE
<!DOCTYPE html>
<html ng-app="myModule" >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body ng-init="priceList='promo03,promo04'">
<div ng-controller="PricingController" >
{{splitArray()}}
</div>
<script>
var myModule = angular.module('myModule',[]);
myModule.controller('PricingController',['$scope', function($scope){
$scope.priceString = $scope.priceList;
$scope.array = [];
$scope.splitArray= function(){
console.log($scope.priceString);
$scope.array = $scope.priceString.split(",");
console.log($scope.array[0]);
console.log($scope.array[1]);
};
}]);
</script>
</body>
</html>
CONSOLE OUTPUT
promo03,promo04
promo03
promo04
promo03,promo04
promo03
promo04
promo03,promo04
promo03
promo04
Expected Output
promo03,promo04
promo03
promo04
This is called for every digest loop of Angular.
If you keep your program running, you'll have even more logs.
To prevent it, call your function INTO your controller, not into a binded value into your html.
For instance :
$scope.splitArray= function(){
console.log($scope.priceString);
$scope.array = $scope.priceString.split(",");
console.log($scope.array[0]);
console.log($scope.array[1]);
};
$scope.splitArray();

Display input value with Ng-Model referenced

I am aware that I cannot set the value of an input when Ng-Nodel is referenced, but I am trying to find a work around.
The html value is being pulled from the URL variable (such as full name or email) that the user has entered in the previous page. Ng-model is being used to store these information. - signUp.php?user_email=$email&fname=$fullNam
Below is an example of what I mean,
<?php
$email = $_GET['user_email'];
$fullName = $_GET['fname'];
?>
<input id="signupformItem" ng-model="user.username" type="email" name="email" value= <?php echo $email; ?> placeholder="Email Address" required> <br>
Any help would be greatly appreciated
I just created a demo for you but I will recommend you to go through some series of tutorial to get better knowledge of the framework or technology(angularjs and javascript) you are going to use in your project.
I created plunk for you. You can visit it here.
Javascript code
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, userService) {
$scope.name = 'World';
$scope.userName = userService.getUsers();
userService.getUserAjax()
.success(function(response) {$scope.names = response[0].Name;});
});
app.service('userService', function($http){
var fac = {};
fac.getUserAjax = function() {
return $http.get("http://www.w3schools.com//website/Customers_JSON.php");
};
fac.getUsers = function(){ return 'John'};
return fac;
});
HTML code
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
by {{userName}}
<p>username loaded by ajax :{{names}}</p>
</body>
</html>
You need to define one service that communicate to your web page using ajax service provided by angular ($http) and call it from the controller and on the success function just pick up the value and assign it to your scope variable. In your case username.
I just used w3schools service url here just for demonstration which would give me a list of users you need to implement php code that would return what you want and use it like described above.
I hope it would have given you basic idea of how to setup angular code to communicate to the server.

Using web-browser control with angularjs

Trying to do below:
(a) Embedded a web browser control inside a winform.
(b) Pass a string data from winform control to webbrowser via Invoking a method in JS.
This JS method further calls the angularJS controller. Call is successful. However, the controller which is used in view does not gets updated.
Snippet below:
Invoking side C# winform snippet:
string testString = "testing";
webBrowser2.Document.InvokeScript("InvokeJSPassingTestString", new object[] { testString });
HTML Side.
<html ng-app="ManagerApp">
<head>
<meta charset="utf-8" />
<title></title>
<script src="Scripts/angular.js"></script>
<script type="text/javascript">
var angularApp = angular.module('ManagerApp', []);
angularApp.controller('ManagerCtrl', ['$scope', function ($scope) {
$scope.customParams = {};
$scope.updateCustomRequest = function (data) {
$scope.customParams.value = data;
alert("$scope.customParams.value :" + $scope.customParams.value);
};
}]);
function InvokeJSPassingTestString(data) {
var dom_el = document.querySelector('[ng-controller="ManagerCtrl"]')
var ng_el = angular.element(dom_el);
var ng_el_scope = ng_el.scope();
var test = ng_el_scope.updateCustomRequest(data);
}
</script>
</head>
<body ng-controller="ManagerCtrl">
Passed parameter from winform to JS to angularJs is as below:
{{ customParams.value }}
</body>
</>
In above snippet - I get the alert but the view {{ customParams.value }} does not gets updated.
Any inputs appreciated.
You code is running outside the angularjs digest cycle, so you need to start a new digest cycle after changing data
$scope.updateCustomRequest = function (data) {
$scope.$apply(function () {
$scope.customParams.value = data;
alert("$scope.customParams.value :" + $scope.customParams.value);
});
};
How to update bindings

Categories