Just new to angularjs and have been finding a way to get an app running. Very simple and straight forward:
Angular controller:
(function () {
'use strict';
angular
.module('myQuotesApp')
.controller('QuotesController', QuotesController);
QuotesController.$inject = ['$scope', 'Quotes'];
function QuotesController($scope, Quotes) {
$scope.quotes = Quotes.query();
}
})();
This is the service class of angularjs
(function () {
'use strict';
var QuotesService = angular.module('QuotesService', '[ngResource]');
QuotesService.factory('Quotes', ['$resource', function ($resource) {
return $resource('/api/quotes/', {}, {
query: { method: 'GET', params: {}, isArray:true }
});
}]);
})();
THis is the html file:
<!DOCTYPE html>
<html ng-app="myQuotesApp">
<head>
<meta charset="utf-8" />
<title>My Quotes App</title>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular-resource/angular-resource.min.js"></script>
<script src="lib/angular-route/angular-route.min.js"></script>
<script src="/app.js"></script>
</head>
<body ng-cloak>
<div ng-controller="QuotesController">
<H2>List of Quotes</H2>
<ul>
<li ng-repeat="quote in quotes">
<p> "{{quote.Content}}" - {{quote.Author}}</p>
</li>
</ul>
</div>
</body>
</html>
The server side model:
public class Quote
{
public int Id { get; set; }
public string Author { get; set; }
public string Comment { get; set; }
}
The server side controller:
public IEnumerable<Quote> Get()
{
return new List<Quote> {
new Quote { Id=1, Author="James John", Comment="This guy is good to work with."},
new Quote { Id=2, Author="Larry Page", Comment="This is one of the best guys in the IT world"},
new Quote { Id=3, Author="Goodwill Adebayo", Comment="It is always good to work with God." }
};
}
Whenever I run the app it displays a blank page. I checked the browser console and I got this error:
angular.js:4640Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=myQuotesApp&p1=Erro…http%3A%2F%2Flocalhost%3A60261%2Flib%2Fangular%2Fangular.min.js%3A20%3A390)
jquery-1.9.0.js:1 '//# sourceURL' and '//# sourceMappingURL' are deprecated, please use '//# sourceURL=' and '//# sourceMappingURL=' instead.
You are missing few pieces. You'll need to create myQuotesApp module first before using it.
Working Example at Plunker - http://plnkr.co/edit/l3UmoDjjGhaQq0JNjtsF.
(function () {
'use strict';
angular
.module('myQuotesApp', ['ngResource']) // <----
.controller('QuotesController', QuotesController);
QuotesController.$inject = ['$scope', 'QuotesService'];
function QuotesController($scope, QuotesService) {
$scope.quotes = QuotesService.query();
}
angular
.module('myQuotesApp')
.factory('QuotesService', ['$resource', function ($resource) {
var query = function() {
return [{Content: "One", Author: "John"},
{Content: "Two", Author: "Eric"}]
}
return {
query: query
}
}]);
})();
How to pull data from Web API
You just need to update QuotesService to use $resource.
(function () {
'use strict';
angular
.module('myQuotesApp', ['ngResource'])
.controller('QuotesController', QuotesController);
QuotesController.$inject = ['$scope', 'QuotesService'];
function QuotesController($scope, QuotesService) {
$scope.quotes = QuotesService.query();
console.log($scope.quotes);
}
angular
.module('myQuotesApp')
.factory('QuotesService', ['$resource', function ($resource) {
return $resource('/api/quotes/', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
}]);
})();
Related
I have posted some code which i write while i am learning angularjs. I`ve made a resource file to get rest calls from the back-end and a controller where i am calling this function but i do not know how to call the controller in the index.html file.
controller
(function () {
'use strict';
angular.module('carApp').controller('HomeController',
HomeController);
HomeController.$inject = ['$rootScope', '$scope', 'HomeResourceService'];
function HomeController($rootScope, $scope, HomeResourceService) {
var vm = this;
function loadTestData(key, value) {
vm.test = undefined;
return HomeResourceService.getTestData(key,
value).then(function (response) {
vm.test = response.data;
}).catch(function () {
console.log('Error when try to get test data!');
});
}
}
})();
index.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>SCARS HOME</title>
</head>
<body ng-app="carApp">
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js">
</script>
<script src="app/app.js"></script>
<script src="app/home/home-resource.js"></script>
<script src="app/home/home-controller.js"></script>
</body>
</html>
resource
(function() {
'use strict';
angular.module('carApp').factory('HomeResourceService',
HomeResourceService);
HomeResourceService.$inject = [ '$http' ];
function HomeResourceService($http) {
var service = {};
var getTestDataUrl = '/api/data';
service.getTestData = function(key, value) {
return $http({
method : "GET",
url : getTestDataUrl,
params : {
operator : key,
market : value
}
});
};
return service;
}
})();
you can all controller using ng-controller provided with controller name.In your case it is HomeController.
For example: if you have some login page and you want to call loginController in your login page, you can call it like below code snippet.
<div ng-controller="LoginController as login" class="col-xs-12 loginForm">
<div class="center-deck">
</div>
</div>
and your controller will be like that:-
(function() {
"use strict";
angular.module("login").controller("LoginController", LoginController);
LoginController.$inject = ["$location",'$rootScope', '$window', '$scope'];
function LoginController($location, $rootScope, $window, $scope) {
var _this = this;
$rootScope.showHeader = false;
$scope.loginError = false;
_this.authenticate = authenticate;
function authenticate() {
if($scope.login.username === "mail id" && $scope.login.password === "your password") {
$location.path('/dashboard');
$scope.loginError = false;
} else {
$scope.loginError = true;
$location.path("/login");
}
}
}
})();
It show how you can implement login call functionality in your project.
when i debug my controller, it stuck at the initialization of the controller and doesn't get past it
here is the app
var app = angular.module('app', []);
and here is the controller and it's service
app.controller('UsersController', function ($scope, UsersService) {
$scope.User = [];
$scope.Image = [];
$scope.CV = [];
alert("Controller");
$scope.GetUserProfile = function (ID) {
alert("in");
UsersService.GetUserData(ID, function (Result) {
if (Result.success == true) {
$scope.User = Result.Content;
}
});
}
});
app.service('UsersService', function ($http) {
this.GetUserData = function (UserID,callback) {
var req = {
method: 'GET',
url: 'http://localhost:7598/tb/Profile/GetProfileByID',
headers: {
'Authorization': 'No Authentication'
},
params: {
'ID': UserID
}
}
$http(req).success(callback);
}
});
and in html i reference the Angular js file and the App file and the Controller file
here is the HTML
<script src="~/Scripts/angular.min.js"></script>
<script src="~/ScriptControllers/MainApp.js"></script>
<script src="~/ScriptControllers/UsersController.js"></script>
<div class="card hovercard" ng-controller="UsersController">
<div class="card-background" ng-init="GetUserProfile(5)">
It seems that you're missing an ng-app directive in the html, according to the html and js code you've posted. The browser just parses the js code but does not execute it.
<body ng-app="app"> ... </body>
Working example of your code: here
How after click on button Add open View located at /Home/CreateItem. What i need to write in
$scope.Add = function() {
console.log('working');
}
Index.cshtml:
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/MyScript/Custom.js"></script>
<script src="~/Scripts/angular-animate/angular-animate.min.js"></script>
<script src="~/Scripts/angular-ui/ui-bootstrap.min.js"></script>
<script src="~/Scripts/angular-ui/ui-bootstrap-tpls.min.js"></script>
<div ng-controller="Second">
<button ng-click="Add()">Add</button>
</div>
HomeController:
namespace MvcApplication6.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public JsonResult GetData()
{
string data = "From controller";
return Json(data, JsonRequestBehavior.AllowGet);
}
public ActionResult CreateItem()
{
return View();
}
}
}
Controller.js
var app = angular.module('MyApp', ['ngAnimate', 'ui.bootstrap']);
app.controller('Second', function ($scope, sharedProperties) {
$scope.Add = function() {
// How to redirect to Home/CreateItem ?
}
});
OK
app.controller('Second', function ($scope, sharedProperties,$location) {
$scope.Add = function() {
$location.path("/Home/CreateItem");
}
});
BETTER
app.controller('Second',["$http","sharedProperties","$location", function ($scope, sharedProperties,$location) {
$scope.Add = function() {
$location.path("/Home/CreateItem");
}
}]);
The Better way is better, because it enables you to minify your angular code. By expliciting telling the angular engine that you are expecting $http as param 1 and sharedProperties as param2, a minifier can change those variable names to x and y thus making your javascript smaller.
I have the following Angular 1.5 component:
(function () {
'use strict';
angular
.module('EmployeeInformation')
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', EmployeeDetail);
var EmployeeDetail = {
templateUrl: '../views/components/employeeDetail.html',
controller: 'EmployeeDetailCtrl as empdetail',
bindings: {
employee: '<'
}
};
function EmployeeDetailCtrl() { }
})();
Based on the examples on Angular's site, it seems correct to me. However, when I include the file on my page, I get an error saying that it cannot register the component:
[$injector:modulerr] Failed to instantiate module EmployeeInformation due to:
TypeError: Cannot read property 'controller' of undefined
at $CompileProvider.registerComponent [as component]
If I remove the reference to this component, the page loads fine. Does anyone have any idea what I'm doing wrong?
EDIT: I have a service in the same module composed similarly (that is wrapped in a function and without an empty array - see below) that works correctly:
(function () {
'use strict';
angular
.module('EmployeeInformation')
.service('EmployeeService', EmployeeService);
EmployeeService.$inject = ['$http'];
function EmployeeService($http) {
var apiPrefix = 'http://dvlemployees/api/employees';
this.find = find;
this.get = get;
this.getOne = getOne;
function find(queryObj) { }
function get() { }
function getOne(empNumber) { }
})();
EDIT2: Thanks to #Frondor, I figured out the true problem was that I was calling angular.component on the object before I had defined it. Moving the var EmployeeDetail section to the top fixed the problem.
JavaScript
(function(angular) {
'use strict';
angular.module('EmployeeInformation', [])
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', {
templateUrl: 'view.html',
controller: EmployeeDetailCtrl,
bindings: {
hello: '='
}
});
function EmployeeDetailCtrl(){
this.world = 'World!';
}
})(window.angular);
HTML
<body ng-app="EmployeeInformation">
<!-- components match only elements -->
<div ng-controller="EmployeeDetailCtrl as ctrl">
<h1>
<employee-detail hello="'Hello'"></employee-detail>
</h1>
</div>
</body>
view.html
<span>{{$ctrl.hello}} {{$ctrl.world}}</span>
You need to specify an empty array after the module's name, even if you are not using any dependency on your app.
Live example:
http://plnkr.co/edit/8TbRcg5LBsdlqxLkUccJ?p=preview
Try it:
(function (angular) {
'use strict';
angular
.module('EmployeeInformation', [])
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', EmployeeDetail)
;
var EmployeeDetail = {
templateUrl: '../views/components/employeeDetail.html',
controller: 'EmployeeDetailCtrl as empdetail',
bindings: {
employee: '<'
}
};
function EmployeeDetailCtrl() { }
})(angular);
I would like to use i18n and i10n in my Angular app.
I read that Angular-translate can help with this, however, it doesn't work for me.
In my index.html:
<!DOCTYPE html>
<html ng-app="eApp">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="../common/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../common/css/style.css" />
<title></title>
</head>
<body ng-controller="AppCtrl">
<div id="container" ng-view></div>
<!--- Libs Js files --->
<script type="text/javascript" src="../vendor/angularjs/angular.min.js"></script>
<script type="text/javascript" src="../vendor/angularjs/angular-route.min.js"></script>
<script type="text/javascript" src="../vendor/angularjs/angular-translate.min.js"></script>
</body>
</html>
In my eApp.js:
var eApp = angular.module('elbitApp', ['ngRoute', 'ui.bootstrap', 'config', 'pascalprecht.translate']);
// configure our routes
eApp.config(["$routeProvider",
function ($routeProvider) {
$routeProvider
// route for the home page
.when('/c', {
templateUrl: 'c/partials/c.html',
controller: 'CController'
})
// route for the about page
.when('/de', {
templateUrl: 'd/partials/dE.html',
controller: 'DEController',
resolve: {
data: function (DDataService) {
return DDataService.loadData().then(function (response) {
return response.data;
});
}
}
})
// route for the contact page
.when('/di', {
templateUrl: 'd/partials/di.html',
controller: 'DIController',
resolve: {
data: function (DDataService) {
return DDataService.loadData().then(function (response) {
return response.data;
});
}
}
}).otherwise({
redirectTo: '/di'
});
}]).config(["$httpProvider",
function ($httpProvider) {
// Configure the $httpProvider to parse date with date transformer
$httpProvider.defaults.transformResponse.push(function (responseData) {
convertDateStringsToDates(responseData);
return responseData;
});
}]).config(["$translateProvider",
function ($translateProvider) {
$translateProvider.translations('en', {
"TITLE": 'Hello',
"FOO": 'This is a paragraph.',
"BUTTON_LANG_EN": 'english',
"BUTTON_LANG_DE": 'german'
});
$translateProvider.translations('de', {
"TITLE": 'Hallo',
"FOO": 'Dies ist ein Paragraph.',
"BUTTON_LANG_EN": 'englisch',
"BUTTON_LANG_DE": 'deutsch'
});
$translateProvider.preferredLanguage('en');
}]);
// main controller that catches resolving issues of the other controllers
eApp.controller('AppCtrl', function ($rootScope) {
$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
alert("Cant resolve the request of the controller "); //TODO: add URL + additional data.
})
});
In this file I defined my app and added the $translateProvider and two dictionaries.
Afterwards I got to my deController.js:
eApp.controller('DispatcherEventsController', ['$scope', '$route', '$translate',
function($scope, $route, $translate){
var data = $route.current.locals.data;
$scope.title = $translate.instant("FOO");
$scope.switchLanguage = function(languageKey){
$translate.use(languageKey);
};
}]);
In de.html I added a h1 tag with FOO and in a click I would like to change to German:
<h1>{{title |translate}}</h1>
<h1 translate="{{title}}"></h1>
<button type="button" id="searchButton" class="btn btn-default" ng-click="switchLanguage('de')">German</button>
I don't get any problem, but nothing happens. I expected that the English title will be converted to German title.
What can I do to make this work?
It works well for me. Here is a jsFiddle DEMO.
In this case, you want to bind $scope.title with translation key "FOO".
You should change the value of $scope.title dynamically in the switchLanguage function. Then view will be updated accordingly.
//default value
$scope.title = $translate.instant("HEADLINE");
$scope.switchLanguage = function(key){
$translate.use(key);
$scope.title = $translate.instant("HEADLINE");
}
In my opinion, maybe use translation key is a better way than scope data binding. You don't have to maitain the value of key manually.
<h1>{{'FOO' | translate}}</h1>
According to the error msg you provided, maybe you could check if there is any typo syntax in your controller.
Should be
$translate.use(languageKey)
Not
$translate.uses(languageKey)
Though not directly related to your question - you must remember to set the preferred language in the translations.js file, or whatever its name is that you define your key-value translations. Otherwise it will just default to whatever the key is.
...
GREETING: 'Hello World!',
...
$translateProvider.preferredLanguage('en');
Without this line, when doing this:
<h2>{{'GREETING'|translate}}</h2>
Would appear as just GREETING instead of the 'Hello World.'