I am trying to call a node function when loading a page with angular, but for some reason the function does not get called. I have the ng-app and controller specified and I figured I would just put the api call in the controller constructor. Here is the code for the page:
<!doctype html>
<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="landingPage">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>my page</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="core.js"></script>
</head>
<!-- SET THE CONTROLLER AND GET ALL GATEWAYS -->
<body ng-controller="mainController">
And then my core.js file is in the same directory which holds the controller has the controller:
var loadingCtrl = angular.module('landingPage', []);
function mainController($scope, $http) {
console.log('loading gateways');
// when landing on the page, get all gateways and show them
$http.get('/api/gateways')
.success(function(data) {
$scope.gateways = data;
console.log('got response');
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}
I never see any of the log statements....
I think you just need to change
function mainController($scope, $http) {
//your code here
}
to
angular.module('landingPage').controller('mainController', function($scope, $http) {
//your code here
});
To let angular know the controller exists.
Try array notation for dependency injection like below.
angular.module('landingPage', []).controller('mainController',['$scope','$http', function($scope, $http) {
console.log('loading gateways');
// when landing on the page, get all gateways and show them
$http.get('/api/gateways')
.success(function(data) {
$scope.gateways = data;
console.log('got response');
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}]);
Check the Plunker.
But I would suggest to use factory service for loading external data instead loading it inside controller as you can reuse the same service in different controllers.
Sample code with factory service
'use strict';
angular.module('landingPage', []).controller('mainController',['$scope','$http','gatewayService', function($scope, $http,gatewayService) {
console.log('loading gateways');
// when landing on the page, get all gateways and show them
$scope.gateways = gatewayService.getData();
}]).factory('gatewayService', ['$http',function($http){
return {
getData: function() {
return $http.get('/api/gateways')
.success(function(data) {
return data
console.log('got response');
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
return data;
});
}
};
}]);
Check Plunkr
Related
I'm trying to inject my factory into a controller. If I list the factory as one of the controller's parameters, I get this error:
Error: [$injector:unpr] Unknown provider: wordRushFacProvider <- wordRushFac <- wordrushCtrl
http://errors.angularjs.org/1.6.1/$injector/unpr?p0=wordRushFacProvider%20%3C-%20wordRushFac%20%3C-%20wordrushCtrl
Here is the code for my factory:
(function() {
"use strict";
angular
.module("wordrush")
.factory("wordRushFac", function($http) {
function getValidWords() {
return $http.get('../data/valid-words.txt');
}
return {
getValidWords : getValidWords
}
})
})
And the code for my controller:
(function() {
'use strict'
angular
.module('wordrush')
.controller('wordrushCtrl', function($scope, $http, wordRushFac) {
wordRushFac.getValidWords().then(function(words) {
$scope.words = words.data;
});
$scope.words = 'Hello'
});
})();
And for my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Word Rush</title>
<link rel="stylesheet" href="node_modules/angular-material/angular-material.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="node_modules/angular/angular.js"></script>
<script src="scripts/app.js"></script>
<script src="components/wordrush.ctr.js"></script>
<script src="components/wordrush.fac.js"></script>
</head>
<body ng-app="wordrush" ng-controller="wordrushCtrl">
<h1> {{ words }} </h1>
</body>
</html>
And for my app.js:
angular
.module('wordrush', ['ngMaterial'])
.config(function($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('green');
})
I made a program with code identical to this except the names and variables were changed, and it worked fine. So what am I doing wrong here?
Here is a plunkr that says "Hello": https://plnkr.co/edit/MyxcXQ8YI4QYqeFsyVJz?p=preview
You have an extra set of open / close parenthesis in your controller definition, remove those:
angular
.module('wordrush')
.controller('wordrushCtrl', function($scope, $http, wordRushFac) {
wordRushFac.getValidWords().then(function(words) {
$scope.words = words.data;
});
$scope.words = 'Hello'
});
Also, are you sure you are including the ng-material JS file? I didn't see that listed in your HTML.
You're not injecting in the controller, should be:
.controller('wordrushCtrl', ['$scope', '$http', 'wordRushFac', function($scope, $http, wordRushFac) {
// Rest of controller code;
}]);
Switch your scripts. Factory script should be first then controller
Ther order should be,
<script src="scripts/app.js"></script>
<script src="components/wordrush.fac.js"></script>
<script src="components/wordrush.ctr.js"></script>
DEMO
I made the following changes and it worked fine.
(function() {
"use strict";
angular
.module("wordrush")
.factory("wordRushFac", function($http) {
function getValidWords() {
return $http.get('../data/valid-words.txt');
};
return {
getValidWords : getValidWords
};
});
}());
I just started learning Angular and I've looked on SO for a solution to load a JSON file using angular and I've done what other people have posted a solutions but I cannot get the data from my json file to show for some reason.
my json file (test.json) is simple:
{
"array": [
{"thing": "thing1"},
{"thing": "thing2"},
{"thing": "thing3"}
],
"name": "robert"
}
this is my js file:
var myMod = angular.module("myMod", []);
myMod.controller("myCont", function ($scope, $http) {
$scope.thing = "hi";
$http.get("/test.json")
.success(function (data) {
$scope.stuff = data.array;
$scope.name = data.name;
})
.error(function (data) {
console.log("there was an error");
});
});
and i'm trying to just display the name like this but only {{name}} shows:
<html ng-app="myMod">
<head>
<script src="angular.js"></script>
<script src="testing.js"></script>
</head>
<body ng-controller="myCont">
{{stuff}}
</body>
</html>
I think you had typo, you should inject $http(responsible to make an ajax call) dependency instead of $html(doesn't exist in angular)
You should change code this way.
myMod.controller("myCont", function ($scope, $html) {
to
myMod.controller("myCont", function ($scope, $http) {
As Pankaj Parkar has stated, $http is what you need.
Here is a plunker I created with it working: http://plnkr.co/edit/d0DDU29uitMcwK6qA7kx?p=preview
app.js file with $http instead of $html:
var myMod = angular.module("myMod", []);
myMod.controller("myCont", function ($scope, $http) {
$scope.thing = "hi";
$http.get("test.json")
.success(function (data) {
$scope.stuff = data.array;
$scope.name = data.name;
})
.error(function (data) {
console.log("there was an error");
});
});
If anyone trying this is getting the error:
$http.get(…).success is not a function
Apparently the syntax changed for Angular >1.6. The accepted answer here has new syntax: $http.get(...).success is not a function
I am trying to set a header value based on the value in my controller. I have the header sending when I am hard coding it as shown below but how can I pass the value from the controller into the ngResource get request,
eg I want the value of anything in the headers to be the value from my controller.
var app = angular.module('app', ['ngResource']);
app.factory('UserService', function ($resource) {
return $resource('http://jsonplaceholder.typicode.com/users/:user',{user: "#user"},{
get: {
method: 'GET',
headers: { 'something': 'anything' }
}
});
});
app.controller('TestCtrl', function($scope, $resource, UserService) {
$scope.test = "text";
UserService.get({
user: 2
}, function(data) {
$scope.id = data.id;
}, function(err) {
console.log(err);
});
});
<!doctype html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title ng-bind="title" ng-cloak>Restaurant</title>
</head>
<body ng-controller="TestCtrl">
id - {{id}}
<!-- Don't forget to load angularjs AND angular-resource.js -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-resource.js"></script>
<!--Controllers-->
</body>
</html>
I'm trying angular for the first time to get a list of accounts from an API and display it in a simple list. The api is on a separate domain. So far I have the following in my app.js
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope){
// when landing on the page, get all todos and show them
$http.get('http://api.example.com/accounts')
.success(function(data) {
$scope.accounts = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
});
And my index.html
<!DOCTYPE html>
<html>
<script src="bower_components/angular/angular.js"></script>
<script src="app/app.js"></script>
<body ng-app="myApp" ng-controller="myController">
<ul ng-repeat="account in accounts">
<li >
{{ account.name }}
</li>
</ul>
</body>
And a sample response.
[
{
"name": "Discover",
"_id": "55d532da7fc30ff81f000008",
"__v": 0
},
{
"name": "Citi",
"_id": "55d6b9967fc30ff81f000009",
"__v": 0
}
]
I don't seem to get it to work. All I get is a blank page and the console shows this error in chrome:
'mainController()' is not a function, got undefined
You controller should look like as below : You have missed some dependencies.
myApp.controller("myController", function ($scope, $http) {
// when landing on the page, get all todos and show them
$http.get('http://api.example.com/accounts')
.success(function (data) {
$scope.accounts = data;
console.log(data);
})
.error(function (data) {
console.log('Error: ' + data);
});
});
There may be issue with cross origin request if your app and rest and on different domains.
Let me know the output in your browser's console.
Your application should look like as below :
/**
* #name myApp
*
* Lets create angular application module
* if second parameter is passed with enpty array [] or with dependecies , is * called angular module setter
*
* angular.module('myApp', []); Setter
* angular.module('myApp'); Getter
*/
angular
.module('myApp', []);
/**
* Lets create controlller
*/
angular
.module('myApp')
.controller('myController', ['MainFactory', '$scope',
function(MainFactory, $scope) {
getAllAcounts();
function getAllAcounts() {
MainFactory.getAccounts().success(function(data) {
$scope.accounts = data;
console.log(data);
}).error(function(data) {
console.log('Error: ' + data);
});
}
}
]);
/**
* Lets create factory
*/
angular
.module('myApp')
.factory('MainFactory', ['$http',
function($http) {
var factory = factory || {};
factory.getAccounts = function() {
return $http.get('http://api.example.com/accounts');
};
return factory;
}
]);
HTML :
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script data-require="jquery#2.0.0" data-semver="2.0.0" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script data-require="bootstrap#3.3.5" data-semver="3.3.5" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
</head>
<body ng-controller="myController">
<ul ng-repeat="account in accounts">
<li>
{{ account.name }}
</li>
</ul>
</body>
</html>
I am entirely new to AngularJS. The task is however simple: to parse XML file from the url and make a table out of it.
Yet somehow angular doesn't load. I searched similar questions, but neither worked. My index.html:
<!doctype html>
<html ng-app="myApp">
<head>
<title>jj</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular.intellisense.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/myscript.js"></script>
</head>
<body>
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">Text.</p>
</div>
<div ng-controller="AppController">
<h3>for example 2+3= {{3+2}}</h3>
</div>
</div>
</body>
</html>
I should get 5 instead of 2+3 if angular is loaded?
myscript.js currently looks like:
angular.module('myApp.service', []).
myApp.factory('DataSource', ['$http', function ($http) {
return {
get: function(file,callback,transform){
$http.get(
file,
{transformResponse:transform}
).
success(function(data, status) {
console.log("Request succeeded");
callback(data);
}).
error(function(data, status) {
console.log("Request failed " + status);
});
}
}
}]);
angular.module('myApp', ['myApp.service']);
var AppController = function ($scope, DataSource) {
var SOURCE_FILE = "guitars.xml";
xmlTransform = function (data) {
console.log("transform data");
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json.customers.customer;
};
setData = function (data) {
$scope.dataSet = data;
};
DataSource.get(SOURCE_FILE, setData, xmlTransform);
};
Can you give me some advice?
It has to do with your syntax. I believe you have 2 errors. In your myscript.js you are declaring 2 modules. In your first module you are incorrectly declaring a factory. Use .factory not myApp.factory
angular.module('myApp.service', [])
.factory('DataSource', ['$http', function ($http) {
return {
// do something
}
}]);
In your second module you declare a function called AppController instead of calling the .controller angular method. Do this instead:
angular.module('myApp', ['myApp.service'])
.controller('AppController', ['$scope', 'DataSource', function ($scope, DataSource) {
// controller code
}]);
You can accomplish your program in a sole module by using a construct similar to what follows:
var app = angular.module('myApp', []);
app.controller('AppController', function($scope, DataSource) {
// code
});
app.factory('DataSource', ['$http', function($http) {
// code
}]);
Basically, create a variable for your app module, then call controller and factory, and pass your factory into your controller.