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.
Related
I have 2 files. First one :
<script>
var demo=angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
$http.get('http://localhost/scores').then(function(response) {
$scope.scores = response.data;
});
});
</script>
Another file index.html
<head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="scoresCtrl.js"></script>
<script>
function run(){
var data=angular.element(document.getElementById("scoresBodyId")).scope().scores;
alert(data);
}
</script></head>
<body onload="run()" id="scoresBodyId" ng-controller="scoresCtrl" >
</body>
When I tried to display alert(data) , I got undefined
but when I replace onload by onclick , after Clicking I obtained my value. I would like to use onload. Thanks for your explanation and your help.
You need to change onload to ng-init to call your function on body
Controller
var demo = angular.module('demo', []);
demo.controller('scoresCtrl', function($scope, $http) {
$scope.run = function() {
$http.get('http://localhost/scores').then(function(response) {
$scope.scores = response.data;
alert($scope.scores);
});
}
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="scoresCtrl.js"></script>
</head>
<body ng-init="run()" id="scoresBodyId" ng-controller="scoresCtrl">
</body>
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.
I am having a problem sending a value of JavaScript variable to Angular js variable. I want to send a value in dataArray variable in JavaScript to Angular js variable $scope.test
html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="angular.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
// $("#fileUpload").load('test.csv');
$.get("test.csv", function(data) {
alert(data);
var rows = data.split("\r\n");
if(rows.length>0){
alert("inside if");
var firstRowCells = GetCSVCells(rows[0], ",");
var dataArray = new Array();
for(var i=1;i<rows.length;i++)
{
var cells = GetCSVCells(rows[i], ",");
var obj = {};
for(var j=0;j<cells.length;j++)
{
obj[firstRowCells[j]] = cells[j];
}
dataArray.push(obj);
}
$("#dvCSV").html('');
alert(dataArray);
$("#dvCSV").append(JSON.stringify(dataArray));
var myjson=JSON.stringify(dataArray);
//alert(myjson);
}
});
function GetCSVCells(row, separator){
return row.split(separator);
}
});
</script>
</head>
<body>
<div id="container">
Test
</div>
<div ng-app="sortApp" ng-controller="mainController">
<div id="dvCSV" ng-model="dataf" ng-bind="bdc">dfsgdfd</div>
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
angular.module('sortApp', [])
.controller('mainController', function($scope) {
window.alert("Angular");
window.alert("asdfad"+$scope.bdc);
$scope.test=$scope.dataf;
window.alert($scope.myjson);
window.alert("test"+$scope.test.value);
You can do this all jquery stuff in angular using http service of angular js.
For simple http service you can refer this link -
http://www.w3schools.com/angular/angular_http.asp
I agree with previous answer. Also its wrong to use $(document).ready along with using angular framework in you application.
Try something like this:
angular.module('sortApp', [])
.service('loadTestCsv' ['$http', function($http) {
return $http.get('test.csv').then(data => {
// do all data processing you need
return data;
});
}]);
.controller('mainController', ['$scope', 'loadTestCsv', function($scope, loadTestCsv) {
loadTestCsv().then(data => {
$scope.data = data;
});
}]);
So I want to inlcude a own service to a angular-script.
But it won't find the servicename, when I put it into the params of my script.
I got this script(script.js):
(function(){
var app = angular.module("Viewer", []);
var MainCtrl = function($scope, viewthis, $http, $interval, $log){
Magic;
};
app.controller("MainController", MainCtrl);
}());
And this is my service(viewthis.js):
(function()
{
var viewthis = function($http)
{
Methods, Magic;
//there is this return in a method:
return $http.get("https://api.github.com/users/" + username);
return
{
method: method
};
};
var module = angular.module("Viewer");
module.factory("viewthis", viewthis);
}());
This is the HTML head:
<head>
<script src="angular.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
<script src="viewthis.js"></script>
</head>
The FireFox-Developement-tool says this in the console:
"Error: [$injector:unpr] http://errors.angularjs.org/1.2.26/$injector/unpr?p0=githubProvider%20%3C-%20github
C/<#file:///Z:/AngularTut/angular.js:6:443
gc/l.$injector<#file:///Z:/AngularTut/angular.js:36:196
c#file:///Z:/AngularTut/angular.js:34:300
gc/p.$injector<#file:///Z:/AngularTut/angular.js:36:266
c#file:///Z:/AngularTut/angular.js:34:300
d#file:///Z:/AngularTut/angular.js:35:1
f/<.instantiate#file:///Z:/AngularTut/angular.js:35:163
Pd/this.$get</<#file:///Z:/AngularTut/angular.js:67:415
N/<#file:///Z:/AngularTut/angular.js:54:23
r#file:///Z:/AngularTut/angular.js:7:369
N#file:///Z:/AngularTut/angular.js:53:393
g#file:///Z:/AngularTut/angular.js:47:256
g#file:///Z:/AngularTut/angular.js:47:256
z/<#file:///Z:/AngularTut/angular.js:46:374
fc/c/</<#file:///Z:/AngularTut/angular.js:18:310
Zd/this.$get</k.prototype.$eval#file:///Z:/AngularTut/angular.js:112:57
Zd/this.$get</k.prototype.$apply#file:///Z:/AngularTut/angular.js:112:341
fc/c/<#file:///Z:/AngularTut/angular.js:18:268
d#file:///Z:/AngularTut/angular.js:35:27
fc/c#file:///Z:/AngularTut/angular.js:18:248
fc#file:///Z:/AngularTut/angular.js:18:380
Xc#file:///Z:/AngularTut/angular.js:17:422
#file:///Z:/AngularTut/angular.js:215:30
a#file:///Z:/AngularTut/angular.js:145:67
oe/c/<#file:///Z:/AngularTut/angular.js:31:223
r#file:///Z:/AngularTut/angular.js:7:288
oe /c#file:///Z:/AngularTut/angular.js:31:207
"
If i delete "viewthis" from the params, it will build the page. With "viewthis" in it, not.
And if its easy to solve, I am sorry. I am a newbie in javascript...
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