How to send value in JavaScript variable to a Angular js variable - javascript

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

Related

value $scope is undefined

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>

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

creating javascript array along with variables in local storage - AngularJS

Can anyone please tell me how to create arrays like myarray = [] along with other variables in localstorage using angularJS,
ive created variable which is as shown below.
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
<script>
angular.module('app', [
'ngStorage'
]).
controller('Ctrl', function(
$scope,
$localStorage
){
$scope.$storage = $localStorage.$default({
x: 42 // variable
});
});
</script>
</head>
<body ng-controller="Ctrl">
<button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button> + <button ng-click="$storage.y = $storage.y + 1">{{$storage.y}}</button> = {{$storage.x + $storage.y}}
</body>
</html>
It support json, you can store anything except those not supported by JSON:
Demo
<script>
angular.module('app', [
'ngStorage'
]).
controller('Ctrl', function(
$scope,
$localStorage
){
$scope.$storage = $localStorage.$default({
x: 42,
array:[]
});
});
</script>

What am I doing thats causing Unknown Provider when Adding both a service and a filter or multiple services

This is most likely due to my lack of experience and overlooking something fundamental but between SO, the angulajs tutorials and guide as well as Googling and I can't find an explaination or example that I can follow.
I have successfully created a factory and used it in my controller and a filter but Only one or the other. when I try to add both to the module I get Error: Unknown provider: memberFactoryProvider <- memberFactory
my code is below but some questions I have include:
1. When adding the factory and service (or multiple factories/filters) to a module is it enough to create them the same way as you with a single factory i.e.
if I have a number of factories delclared like so:
'use strict';
angular.module('testApp', [])
.factory('factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;
});
angular.module('testApp', [])
.factory('factory2', function () {
var obj = {};
obj.text = "This is another test";
return obj;
});
is it enough to inlcude the two in app.js using angular.module('testApp', ['factory1', 'factory2']);
2. I have noticed some posts online that when creating a filter/factory they append the appname e.g.:
angular.module('testApp', [])
.factory('testApp.factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;});
is this required or personal preference?
Finally below is all my code, as mentioned above, all work indiviually but when I try to combine them I get the error mentioned above, any advice or help is greatly appreciated
index.html
<!DOCTYPE html>
<html data-ng-app="testApp">
<head>
<title>prototype</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<div data-ng-controller="myController">
<br/>
<div data-ng-repeat="n in [] | range:5">
<div data-ng-repeat="">{{test}}</div>
</div>
</div>
<br/>
<br/>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="js/services.js"></script>
<script type="text/javascript" src="js/filters.js"></script>
<script type="text/javascript" src="js/controllers.js"></script>
</body>
</html>
App.js
'use strict';
angular.module('testApp', ['memberFactory', 'range']);
services.js
'use strict';
angular.module('testApp',[])
.factory('memberFactory', function(){
var obj = {};
obj.text = "This is a test";
return obj;
});
filters.js
'use strict';
angular.module('testApp',[]).filter('testApp.range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++)
input.push(i);
return input;
};
});
controllers.js
function myController($scope, memberFactory){
$scope.test= memberFactory.text;
}
First of all you should be doing this
angular.module('testApp', [])
.factory('factory1', function () {
var obj = {};
obj.text = "This is a test";
return obj;
})
.factory('factory2', function () {
var obj = {};
obj.text = "This is another test";
return obj;
});
You shouldn't create 2 modules of the same name.
And I think that this
angular.module('something', ['here', 'is', 'for modules', 'only'];
I think what you are trying to do is this.
You have 2 modules?
var helpers = angular.module('helpers', []);
Then you should do
var app = angular.module('app', ['helpers']);
Then you will have access to all factories that are attached to helpers and app
Say for example you want your filters in another file there are a few ways to do it
var filters = angular.module('filters', []);
filters.filter('name', func...);
Then you include it in your app like so
var app = angular.module('app', ['helpers', 'filters']);

Categories