Controller with this name is not registered - javascript

I am working on school project using angularjs, I don't know why I'm getting this Error: $controller:ctrlreg A controller with this name is not registered.
index.html:
...
<div ng-controller="medscontroller">
<ul>
<li ng-repeat="med in meds | filter:{nom:nom} | orderBy:order">{{med.nom}}</li>
</ul>
</div>
<script >
function medscontroller($scope){
$scope.meds=[
{"nom":"aspirine", "prix":"20"},
{"nom":"doliprane","prix":"15"},
{"nom":"da", "prix":"15"}
];
console.log($scope);
}
</script>

You cannot simply define a controller function like above.
In order for a controller to work, you have to do the following things.
Create an angular app with
var app = angular.module('myApp', []);
Deine a controller for that app with.
app.controller('myCtrl', function($scope) { });
Find a working example here.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>

Related

Angular services giving "TypeError: Cannot read property 'helloConsole' of undefined"

I'm studying AngularJS Services and I'm having a problem.
That's my Angular code:
var app = angular.module("todoListApp");
app.controller('MainController', MainController);
MainController.$inject = ['$scope'];
function MainController($scope, dataService){
$scope.helloConsole = dataService.helloConsole;
};
app.service('dataService', function(){
this.helloConsole = function(){
console.log("console services");
};
});
That's my HTML Code
<div ng-controller="MainController" class="list">
<div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
<div class="actions">
Edit
Save
Delete
</div>
</div>
</div>
I'm trying to make it so that when I click on Save, the console shows me "console services", but it's giving me an error:
angular.js:13424 TypeError: Cannot read property 'helloConsole' of undefined
Proper Angular Structure
you need to change the way you have written your code. It should look more like this
angular.module("todoListApp", [])
.controller('MainController', ['$scope', 'dataService', function($scope, dataService){
$scope.helloConsole = dataService.helloConsole;
}])
.service('dataService', [function(){
this.helloConsole = function(){
console.log("console services");
};
}]);
Also this is a 'data service' is this gettig data with a http call? Because if so then make a factory.
Controllers for business logic
Factories for data requests
Services for things like login
Directives for DOM manipulation
Filters for format
Return a singleton service object from angular.service's second function argument. Also, if you're explicit about the dependencies of your controller, thinks will work a lot clearer/better:
var app = angular.module("todoListApp", []);
app.controller('MainController', ['$scope', 'dataService', MainController]);
function MainController($scope, dataService){
$scope.helloConsole = dataService.helloConsole;
$scope.todos = [{txt:"todo 1"}, {txt:"todo 2"}];
}
app.service('dataService', function(){
return {
helloConsole: function(){
console.log("console services");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<div ng-app="todoListApp">
<div ng-controller="MainController" class="list">
<div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
{{todo.txt}}
<div class="actions">
Edit
Save
Delete
</div>
</div>
</div>
</div>
I rewrote this a little bit so it's easier to understand (for me at least).
I have added a "todos" array to your code just to make the ng-repeat fire.
var app = angular.module("todoListApp",[])
.service('dataService', function(){
this.helloConsole = function(){
console.log("console services");
};
})
.controller('MainController', [ '$scope', 'dataService',function ($scope,dataService) {
$scope.helloConsole = dataService.helloConsole;
$scope.todos = [ {
"todo":"1"
}
]
}])
;

UI-Router for item list Angularjs

I'm facing some problems with my simple code (study), i really need some help to fix this.
First of all i have a php file who provides a json.
app.php
<?php
$dbh = new PDO('mysql:host=localhost;dbname=caio', 'root', '');
$a = $dbh->query("SELECT * FROM usuario");
$b = json_encode($a->fetchAll(PDO::FETCH_ASSOC));
echo $b;
?>
It's a simple json with id, name and surname
Also i have a Js file to get this.
app.js
var meuApp = angular.module('meuApp', ['ui.router']);
meuApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('usuarios.detail', {
url: "/usuarios/{id}",
templateUrl: 'uDetail.html'
});
});
meuApp.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('app.php')
.success(function(data) {
$scope.usuarios = data;
console.log(data);
//just checking in the console...
var id = data[0].id
console.log(id);
var nome = data[0].nome
console.log(nome);
});
}]);
and finally my html file
<html ng-app="meuApp" lang="pt">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="userCtrl">
<ul>
<li ng-repeat="usuario in usuarios">
<a ui-sref="usuarios.detail">{{usuario.nome}}</a>
</li>
</ul>
</div>
</body>
If i want to show, ok the code is working, but i want to click in each name and then the template shows me the id, name and surname of this "person". That's my problem.
Thank you guys.
Here you need to pass person object from one state to another state.
For that you can use params attribute of ui-router. When you click any perticular person at that time you need to pass id also while routing from one state to another because you already configure in url "/usuarios/{id}".
ui-router will match that property from params and will set in url.
Now you can successfully pass clicked object from one state to another. Get that object with $stateParams service of ui-router in controller of usuarios.detail state so that you can display in uDetail.html
meuApp.config(function($stateProvider, $urlRouterProvider,$stateParams){
$stateProvider
.state('usuarios.detail', {
url: "/usuarios/{id}",
params: {
id: null,
person:null
},
templateUrl: 'uDetail.html',
controller: function($scope, $stateParams) {
$scope.portfolioId = $stateParams.id;
$scope.person = $stateParams.person;
console.log("State parameters " + JSON.stringify($stateParams));
}
});
});
and in your template where you are showing the list.
<ul>
<li ng-repeat="usuario in usuarios">
<a ui-sref="usuarios.detail({ id:usuario.id,person:usuario})">{{usuario.nome}}</a>
</li>
</ul>
See above code which I gave for your reference.
You can see this Demo for in detail idea of ui-router.
You need some minor changes in order to get your code working, check the files bellow:
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="userCtrl">
<ul>
<li ng-repeat="user in users">
<a ui-sref="users.detail({id: user.id, user: user})">{{user.name}}</a>
</li>
</ul>
</div>
<div ui-view></div>
</body>
app.js
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider) {
$stateProvider
.state('users', {
abstract: true,
url: 'users',
template: '<div ui-view></div>'
})
.state('users.detail', {
url: '/:id',
templateUrl: 'users.detail.html',
params: {
user: null
},
controller: function($scope, $stateParams) {
$scope.user = $stateParams.user;
}
});
});
app.controller('userCtrl', ['$scope', '$http',
function($scope, $http) {
// replace this with your service call
$scope.users = [{
id: 1,
name: 'john',
surname: 'doe'
}, {
id: 2,
name: 'mary',
surname: 'poppins'
}];
}
]);
user.detail.html
<fieldset>
<div>
<label>id: </label> {{user.id}}
</div>
<div>
<label>name: </label> {{user.name}}
</div>
<div>
<label>surname: </label> {{user.surname}}
</div>
</fieldset>

Angular JS Expression is not working when I use a controller and module

I've just started learning Angular JS but soon I got a problem which I don't know how to resolve.
This code prints:
<h1>{{author[0].name}}</h1>
<p>{{author[0].title+ ', '+author[0].company}}
instead of:
<h1>MKJ</h1>
<p>Web Developer, Student Organization</p>
The code is given here as well:
<!doctype html>
<!-- Declaring the ng-app -->
<html ng-app="myApp">
<head>
<title>Parking</title>
<!-- Importing the angular.js script -->
<script src="lib/angular/angular.min.js"></script>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("MyController", function ($scope){
$scope.author = {
'author': 'MKJ',
'title': 'Web Developer',
'company': 'Student Organization',
};
}
</script>
</head>
<!-- Attaching the view to the MyController -->
<body ng-controller="MyController">
<h1>{{author[0].name}}</h1>
<p>{{author[0].title+ ', '+author[0].company}}
See this snippet or correct the code on JS fiddle?
var myApp = angular.module("myApp", []);
myApp.controller("MyController", function ($scope){
$scope.author = {
'author': 'Ravy VIllalbobs',
'title': 'Staff Author',
'company': 'Lynda.com',
};
}
<div ng-controller="MyController">
<h1>{{author.name}}</h1>
<p>{{author.title+ ', '+author.company}}
</div>
$scope.author is an Object so you don't need to specify index in brackets here
<h1>{{author.name}}</h1>
<p>{{author.title+ ', '+author.company}}
updated fiddle

Why this simple Angular.js example does not work?

I'm reading AngularJS from O'REILLY, and i tried to see how angular works with an example but i can make it functional:
The hello.html :
<html ng-app>
<head>
<script src="angular.js"></script>
<script src="controllers.js"></script>
</head>
<body>
<div ng-controller="HelloController">
<p>{{ greeting.text }}, World</p>
</div>
</body>
</html>
and the logic within the controllers.js :
function HelloController($scope) {
$scope.greeting = { text: 'Hello' };
}
but when i display the hello.html on the browser, i can see {{ greeting.text }}, Hello.
What is wrong here?
You never defined a controller, you just defined a function that happened to have "controller" in the name.
Try initializing the app properly:
var myApp = angular.module('myApp',[]);
myApp.controller('HelloController', ['$scope', function($scope) {
$scope.greeting = {text: 'Hello'};
}]);
https://docs.angularjs.org/guide/controller

AngularJS: values of defined variables inside controller are not getting displayed correctly

I am learning angular.. I have tried to run a small example through pluralsight, but wasn't able to render correct output..
http://plnkr.co/edit/cYEDSW3FrAKeh1SBjUVN?p=preview
HTML
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{text}}</h1>
<div>
<div>First name: {{person.firstName}}</div>
<div>Last name: {{person.lastName}}</div>
<img ng-src="person.imageSrc" title="{{person.firstName}} {{person.lastName}}">
</div>
</body>
</html>
script.js
var MainController = function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
};
I am not able to figure out why angular variables are getting displayed as normal text instead of its assigned value. Experts, kindly help...
There are a few things that need to be changed in your code
you need to create an angular module
var app = angular.module('app', []);
2 add directive to html element
<html ng-app='app'>
need to register MainController against angular module like this:
app.controller('MainController', function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
});
Here is a working demo - http://plnkr.co/edit/i9N2OC75EGZwUTDcKtLB?p=preview
You missed a few steps:
1. Declaring your app
<html ng-app='myApp'>
2. Declaring your controller inside your app module:
angular.module('myApp', [])
.controller('MainController', function($scope) {
var person = {
firstName: "Ajay",
lastName: "Sattikar",
imageSrc: "http://odetocode.com/Images/scott_allen_2.jpg"
};
$scope.text = "Hello Angular!";
$scope.person = person;
})

Categories

Resources