[$injector:nomod], [$injector:modulerr] error in Angular - javascript

I'm very new to angular js and following is my code
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<script type="text/javascript">
(function(angular){
var testAngular = angular.module('testAngular');
testAngular.controller = ("name_controller", function($scope) {console.log("hello");
$scope.name = {
firstName: "null",
lastName: "null",
setName: function(fname, lname) {
if(fname.trim != "") {
this.firstName = fname;
}
if(lname.trim()!="") {
this.lastName = lname;
}
},
getName: function() {
var name_object = $scope.name;
return name_object.firstName+" "+name_object.lastName;
}
};
});
})(window.angular);
</script>
<div ng-app="testAngular" ng-controller="name_controller">
Enter first name: <input type="text" ng-model="name.firstName"><br><br>
Enter last name: <input type="text" ng-model="name.lastName"><br>
<br>
You are entering: {{ name.firstName }}
</div>
Now when I'm trying to run this code I'm getting 2 errors in console as
[$injector:nomod]
and
[$injector:modulerr]
Any idea why exactly this is happening. Some post says I need to include the route module but I'm not using routing any where in my code.

Try to change:
testAngular.controller = ("name_controller", function($scope) {
to
testAngular.controller("name_controller", function($scope) {

Related

Why can't I print the value from input type using AngularJS?

Here is a very simple application that lets the user change his name. However, there is some bug in this code. Whenever the user writes something into input, the change is not reflected in the welcome header.
app.js
'use strict';
angular
.module('angularScopesBug', [])
.controller("WelcomeController", function ($scope) {
$scope.name = 'John Doe';
$scope.getName = function() {
return $scope.name;
};
})
.controller("EditingController", function($scope) {
$scope.editMode = false;
$scope.changeName = function() {
$scope.editMode = true;
};
$scope.closeEditor = function() {
$scope.editMode = false;
};
})
.directive("nameEditor", function () {
return {
template: 'Write your name: <input type="text" ng-model="name">'
};
});
index.html
<div ng-app="angularScopesBug" ng-controller="WelcomeController">
<h1>Hello, {{ getName() }}</h1>
<div ng-controller="EditingController">
<button ng-click="changeName()" ng-show="!editMode">Change your name</button>
<div ng-show="editMode">
<name-editor ng-show="editMode"></name-editor>
<button ng-click="closeEditor()" ng-show="editMode">Close name editor</button>
</div>
</div>
</div>
The header should change according to the input.
Always use an object in ng-model.
Primitives have no inheritance and the nested controller is using a child scope. When that child scope is created it gets the primitive name as value.
When it is an object the object is inherited so that updating property values will be reflected in all references to that object
angular
.module('angularScopesBug', [])
.controller("WelcomeController", function($scope) {
$scope.model = {
name: 'John Doe'
};
})
.controller("EditingController", function($scope) {
// simplified for clarity
})
.directive("nameEditor", function() {
return {
template: 'Write your name: <input type="text" ng-model="model.name">'
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" ></script>
<div ng-app="angularScopesBug" ng-controller="WelcomeController">
<h1>Hello, {{ model.name }}</h1>
<div ng-controller="EditingController">
<button ng-click="editMode = true" ng-show="!editMode">Change your name</button>
<div ng-show="editMode">
<name-editor ng-show="editMode"></name-editor>
<button ng-click="editMode = false" ng-show="editMode">Close name editor</button>
</div>
</div>
</div>
Your two controllers have different $scope values. Since the editor is inside the EditingController $scope, it is changing a .name value in the lower scope, not in the higher WelcomeController $scope.
Try giving yourself a parent method to modify the value;
$scope.changeName = function(str) {
$scope.name = str;
};
And then calling that method with the new name from the child.

Can not get alert in service of angularjs

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="canerApp" ng-controller="canerCtrl">
<button ng-click="click()">
Button click
</button>
<p ng-show="isClicked">
name=
<input type="text" ng-model="caner.name">
<br> surnanme=
<input type="text" ng-model="caner.surname">
<br> age
<select ng-model="caner.age"
ng-options=" person.age as person.age for person in peole" >
</select>
<br> Welcome Message: {{ caner.name + " " + caner.surname+" "+caner.age}}
</p>
</div>
<script type="text/javascript">
var app = angular.module('canerApp', []);
app.controller('canerCtrl', function($scope,$window) {
$window.alert("ctrl");
$scope.caner = {
name: "caner",
surname: "aydin",
age: "22",
};
$scope.peole = [{
age: 1,
name: 'Bob'
}, {
age: 2,
name: 'Alice'
}, {
age: 3,
name: 'Steve'
}];
$scope.isClicked = true;
$scope.click = function(User) {
$window.alert("ctrl fun");
$scope.isClicked = !$scope.isClicked;
$scope.caner.name = User.save;
};
});
app
.factory('User', function($http,$window) { // injectables go here
var backendUrl = "http://localhost:3000";
$window.alert("service");
var service = {
// our factory definition
user: {},
setName: function(newName) {
service.user['name'] = newName;
},
setEmail: function(newEmail) {
service.user['email'] = newEmail;
},
save: function() { $window.alert("service saave");
return $http.post(backendUrl + '/users', {
user: service.user
});
}
};
return service;
});
</script>
</body>
</html>
this is my code. it can be seen here
http://plnkr.co/edit/gP2NcC38JPsabQFacGkb?p=preview
i merged lots of codes. so there are some unnecessary codes.
What i want is when i click, i can see alert of
ctrl fun
and at firsst start, the alert of ctrl
but cant see the alerts in service.
controller should call service but it doesnot call.
the call is here in conroller
$scope.caner.name = User.save;
i tried also
User.save
or $scope.var = User.save
or
$scope.click = function(User,$scope) {
$window.alert("ctrl fun");
$scope.isClicked = !$scope.isClicked;
$scope.caner.name = User.save;
};
});
but this made worse because it did not even give alert of ctrl.
because probably he was using scope of controller.
You need to inject the User factory into your controller otherwise it will not get instantiated:
app.controller('canerCtrl', function($scope,$window,User) {...}
Regarding your service-call, make sure you do not define another User variable in your click-function. $scope and User are already available in the controller.
$scope.click = function() {
$scope.whatever = User.save();
}
However, keep in mind that you return a promise from your save-function, not a name.

error with using resolve angular-bootstrap-ui

I am having difficulties combining both the editing of a current contact and the creation of a new contact. I am able to edit the contact that I click on, however, when I try and click on add new address the following error message -
angular.js:13424 Error: [$injector:unpr] http://errors.angularjs.org/1.5.3/$injector/unpr?p0=editIndexProvider%20%3C-%20editIndex%20%3C-%20ModalCtrl
This is due to using resolve based on the answer here
Factory
'use strict';
var app = angular.module('testApp', ['ngRoute','ui.bootstrap']);
app.factory('addressFactory', function(){
var addressFactory = {};
addressFactory.addressBook = [];
addressFactory.saveAddress = function(name, address){
addressFactory.addressBook.push({
name: name,
address: address
});
};
addressFactory.updateAddress = function(name, address, index){
addressFactory.addressBook[index] = {
name: name,
address: address
};
};
return addressFactory;
})
CONTROLLERS
.app.controller('testCtrl', ['$uibModal', 'addressFactory', function ($uibModal, addressFactory) {
var testCtrl = this;
this.addressBook = addressFactory.addressBook;
this.open = function () {
touchnoteCtrl.modalInstance = $uibModal.open({
templateUrl: 'app/views/partials/add-address.html',
controller: 'ModalCtrl',
controllerAs:'ctrl'
});
}
this.openEdit = function(index) {
touchnoteCtrl.modalInstance = $uibModal.open({
templateUrl: 'app/views/partials/edit-address.html',
controller: 'ModalCtrl',
controllerAs:'ctrl',
resolve: {
editIndex: function () {
return index;
}
}
});
}
}])
.controller('ModalCtrl', ['$uibModalInstance','addressFactory','editIndex', function ($uibModalInstance,addressFactory, editIndex) {
this.addressBook = addressFactory.addressBook;
this.saveAddress = function( name, address) {
addressFactory.saveAddress( name, address);
$uibModalInstance.dismiss('cancel');
}
this.getIndex = editIndex;
console.log(this.getIndex)
this.updateAddress = function(name, address, index) {
addressFactory.updateAddress( name, address, index);
}
this.cancelAddress = function () {
$uibModalInstance.dismiss('cancel');
};
}]);
HTML
home.html
<a ng-click="ctrl.open()">Enter new address</a>
<div ng-repeat="contact in ctrl.addressBook track by $index">
<p class="contactName">{{contact.name}}</p>
<p class="contactAddress">{{contact.address}}</p>
<button ng-click="ctrl.openEdit($index)">Edit Contact</button>
</div>
form.html
<form>
<input ng-model="ctrl.name" type="text">
<input ng-model="ctrl.address" type="text">
</form>
edit-address.html
<h3>Edit address</h3>
<div ng-include="'app/views/partials/form.html'"></div>
<div>
<button ng-click="ctrl.cancelAddress()">Cancel</button>
<button ng-click="ctrl.updateAddress(ctrl.name, ctrl.address, ctrl.getIndex)">Save</button>
</div>
add-address.html
<h3>Add address</h3>
<div ng-include="'app/views/partials/form.html'"></div>
<div>
<button ng-click="ctrl.cancelAddress()">Cancel</button>
<button ng-click="ctrl.addAddress(ctrl.name, ctrl.address)">Save</button>
</div>
You use the same ModalCtrl for both the open and the openEdit function. The open function does not have a resolve parameter. This way, angular cannot resolve the injected editIndex. Try this:
this.open = function () {
touchnoteCtrl.modalInstance = $uibModal.open({
templateUrl: 'app/views/partials/add-address.html',
controller: 'ModalCtrl',
controllerAs:'ctrl',
resolve: {
editIndex: function () {
return undefined;
}
}
});
}
I think you simply miss a module dependency to angular.ui.bootstrap...

AngularJs json URL changer

I'm working on some mega simple weather app in Angular for practice reasons and i'm stuck..
i have a angular json feed like this:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,NL&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
and it loads the feed in to the index.html. its all working and what i wand now is a input form on index that changes the Amsterdam part of the url on js/services/forcast.js where the above code is to another city so people can see their city weather.
See the demo here: http://dev.bigstoef.nl/workspace/shiva/weer/index.html
Ive tryd about all posable options about now and i'm 3 days further and its a no go. What is there correct way here?
First, create a "configurable" service :
app.factory('forecast', ['$http', function($http) {
var city;
var cities = {
amsterdam: 'Amsterdam,NL',
paris: 'Paris,FR'
};
var api_base_url = 'http://api.openweathermap.org/data/2.5/weather';
var other_params = 'lang=NL_nl&units=metric';
return {
setCity: function(cityName){
city = cityName ;
console.log(city);
},
getWeather: function(cityName){
console.log(city);
if(cityName) this.setCity(cityName);
if (!city) throw new Error('City is not defined');
return $http.get(getURI());
}
}
function getURI(){
return api_base_url + '?' + cities[city] + '&' + other_params;
}
}]);
Then you can create a controller like the following:
app.controller('forecastCtrl', ['$scope', 'forecast',function($scope,forecast){
$scope.city = 'amsterdam' ;
$scope.$watch('city',function(){
console.log($scope.city);
forecast.setCity($scope.city);
});
$scope.getWeather = function(){
console.log('get weather');
forecast.getWeather()
.success(function(data){
console.log('success',data);
$scope.weatherData = data;
}).error(function(err){
console.log('error',err);
$scope.weatherError = err;
});
};
}]);
To implement a template as the following
<link rel="stylesheet" href="style.css" />
<div data-ng-controller="forecastCtrl">
<form>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'amsterdam'">Amsterdam
</label>
<br/>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'paris'">Paris
</label>
<br/>
<button data-ng-click="getWeather()">Get Weather</button>
</form>
<p class="weather-data">
{{weatherData}}
</p>
<p class="weather-error">
{{weatherError}}
</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
You can view the code working here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview
You can return a function in your factory. Define your forcast as
app.factory('forecast', ['$http', function($http) {
return {
query: function(city) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
};
}]);
Then in your controller
forecast.query('Amsterdam,NL').success(function(data) {
$scope.weer = data;
});
Change service code to have a dedicated method which you can call multiple times with different parameters (cities):
app.factory('forecast', ['$http', function($http) {
return {
load: function(location) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
}
}]);
Then in controller you would be able to load forecat for other locations when you need:
forecast.load('Amsterdam,NL').then(function(data) {
$scope. weer = data;
});
Demo: http://plnkr.co/edit/GCx35VxRoko314jJ3M7r?p=preview

ng-click is not firing with factory class

I'm new in AngularJS. The following code is not executing after entering the username and password and clicking the login button. The login should execute the login method and populate person data binding object. Anybody knows why is not firing? Thanks.
Factory File
'use strict';
var usermodule = angular.module('retrieveBasicUserInfo', [])
.factory('basicUserInfo', function($http) {
var credentials = {
username: '',
password: ''
};
var person = "";
$http.defaults.useXDomain = true;
var getBasicUserInfo = function (credentials) {
var inputdata = { "Logon": credentials.username, "Pass": credentials.password};
$http.post('http://localhost:23034/api/wmsusers/login',JSON.stringify(inputdata),
{
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).success(function (inputdata) {
person = inputdata[0];
});
};
return {
person: getBasicUserInfo
};
});
JavaScript File
'use strict';
var usermodule = angular.module('wms', ['retrieveBasicUserInfo'])
.controller('userAuthentication', ['basicUserInfo', function ($scope, basicUserInfo) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function (credentials) {
console.log(credentials)
$scope.person = basicUserInfo.getBasicUserInfo(credentials);
}
}]);
HTML File
<div data-ng-controller="userAuthentication">
<div class="login-panel">
<p>Please complete the following form and click Login to continue:</p>
<form name="loginForm" data-ng-submit="login(credentials)" novalidate>
<label for="username">Username:</label>
<input type="text" id="username"
data-ng-model="credentials.username">
<label for="password">Password:</label>
<input type="password" id="password"
data-ng-model="credentials.password">
<button type="submit">Login</button>
</form>
</div>
<br>
<ul data-ng-model="$parent.person">
<li>Name: {{person.Name}}</li>
<li>Associate Id: {{person.Empid}}</li>
<li>Access Level: {{person.Access}}</li>
</ul>
Please see here http://jsbin.com/vaweja/2/edit.
Your factory returns object with person property and in your controller you are trying to reach getBasicUserInfo so chnage person to getBasicUserInfo. And you missed $scope in your controller definition
change that
return {
person: getBasicUserInfo
};
to
return {
getBasicUserInfo: getBasicUserInfo
};
and
var usermodule = angular.module('wms', ['retrieveBasicUserInfo'])
//and you missed $scope in line bellow after bracket
.controller('userAuthentication', ['$scope','basicUserInfo', function ($scope, basicUserInfo) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function (credentials) {
console.log(credentials)
$scope.person = basicUserInfo.getBasicUserInfo(credentials);
}
}])
;

Categories