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>
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
};
});
}());
Trying to get simple Angular DI working in an existing ASP.NET 5 (Core) project.
Been following this tutorial.
Versions:
AngularJS 1.4.6
ASP.NET 5 (vNext)
Visual Studio 2015
Windows 10
Checked all the basic gotchas with naming and so on. Unclear about how my dependent js-files "controllers.js" & "services.js" are suppose to be discovered by Angular?
If I explicitly include them - which by the tutorial shouldn't be required - I still get
[ng:areq] Argument 'customerController' is not a function, got
undefined
Index.html
<!DOCTYPE html>
<html ng-app="bonusapp">
<head>
<meta charset="utf-8" />
<link href="lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="lib/bootswatch/yeti/bootstrap.min.css" rel="stylesheet" />
<link href="css/main.css" rel="stylesheet" />
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script src="lib/app.js"></script>
<!--<script>angular.bootstrap(document, ['app']);</script>-->
</head>
<body ng-cloak>
<div id="wrapper" ng-controller="customerController">
<div id="main" class="container-fluid">
<div class="row">
<div class="col-md-3">
<h2>Kunder</h2>
<ul>
<li ng-repeat="item in Models">
{{item.FirstName}} {{item.LastName}} <a>Redigera</a> <a>Radera</a>
</li>
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/jquery-validation/dist/jquery.validate.js"></script>
<script type="text/javascript" src="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</body>
</html>
app.js
(function () {
'use strict';
// Define module "app"
angular.module('bonusapp', [
// Angular modules
'ngRoute',
'ngResource',
// Custom modules
'customerService'
// 3rd Party Modules
]);
})();
controllers.js
(function () {
'use strict';
// Assign controller to app
angular
.module('bonusapp')
.controller('customerController', [
customerController]);
// $inject() method call is required to enable the controller to work with minification.
customerController.$inject = [
'$scope',
'Customers'
];
// Construct controller
function customerController($scope, Customers) {
// Populate model from service
$scope.Models = Customers.get();
}
})();
services.js
(function() {
'use strict';
var customerService =
angular
.module('customerService', ['ngResource']);
customerService
.factory('Customers',
['$resource'],
function ($resource) {
return $resource('/api/customers', {}, {
// Service call to get Customers
get: {
method: 'GET',
params: {},
isArray: true
}
});
}
);
})();
As Win suggested, I needed to:
Fix the include order to put jQuery first
Include all my JS files
But I still had some issues. For reference, here are the fixed scripts:
controller.js
(function () {
'use strict';
// Construct controller
// Remarks: controller is now declared FIRST
var customerController = function ($scope, Customers) {
$scope.Title = "Title";
// Populate model from service
$scope.Models = Customers.get();
}
// $inject() method call is required to enable the controller to work with minification.
customerController.$inject = [
'$scope',
'Customers'
];
// Assign controller to app
angular
.module('bonusapp')
.controller('customerController',
customerController);
})();
services.js
(function() {
'use strict';
var customerService =
angular
.module('customerService',
['ngResource']);
customerService
.factory('Customers',
['$resource',
function ($resource) {
return $resource('/api/customers', {}, {
// Service call to get Customers
// Remarks: 'get' in single quotes
'get': {
method: 'GET',
params: {},
isArray: true
}
});
}
]);
})();
You need to include controller.js and services.js files.
In addition, you need to move jquery before angular.js.
<script type="text/javascript" src="lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="lib/angular/angular.js"></script>
<script type="text/javascript" src="lib/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="lib/angular-route/angular-route.js"></script>
<script src="lib/app.js"></script>
<script src="lib/controllers.js"></script>
<script src="lib/services.js"></script>
FYI: You might also want to look into bundling and magnification, before you publish.
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>
My Controller:
angular.module('apartmentCtrl', [])
.controller('ApartmentController', function ($scope, $http, Apartment) {
$scope.loading = true;
$scope.myLocation = '';
Apartment.get($scope.myLocation).success(function (data) {
$scope.apartments = data;
$scope.loading = false;
});
});
My Service
angular.module('apartmentService', [])
.factory('Apartment', function ($http) {
return {
get: function (myLocation) {
//return $http.get('/api/apartments');
return $http({
method: 'GET',
url: '/api/apartments',
//headers: {'Content-Type': 'application/x-www-form-urlencoded'},
params: {location: myLocation}
});
}
};
});
My HTML:
<input type="text" name="myLocation" class="form-control" ng-model="myLocation">
How can I get data from GET method by AngularJS and pass it to params
If you want to pass some value from your form as "location", you should bind it to your model, and explicitly pass it to your factory get function.
I have a working example here, it just does a window alert showing you the typed in data, in place of the $http call, but the idea is the same.
http://plnkr.co/edit/fRra6RfQrSZb8rzrm4XF?p=preview
Html:
<!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.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<form ng-submit="getIt()">
<input type="text" ng-model="myLocation"/>
<input type="submit"/>
</form>
</body>
</html>
Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, Apartment) {
$scope.name = 'World';
$scope.myLocation = 'Hollywood';
$scope.getIt = function() {
Apartment.get($scope.myLocation);
}
});
app.factory('Apartment', function ($window) {
return {
get: function (whatLocation) {
$window.alert(whatLocation);
}
};
});
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