Controller error in Angular Script - [$injector:modulerr] - javascript

I'm not sure about the controller syntax. I keep getting an [$injector:modulerr] error which leads me to believe that it's the controller playing up but I'm lost otherwise. My main objective at the moment is that I'm trying to "get" and display all the results from a couchdb database.
<div ng-app="guestBook">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
<script>
var guestBook = angular.module('guestBook', ['ngRoute'])
guestBook.controller('CouchController', ['$scope', '$http', '$get', function ($scope, $http, $get) {
// View everything in database
$scope.view = function () {
var json = {};
var url = "https://sophia.iriscouch.com/guestbook/_all_docs";
$get({
url: url,
method: 'GET',
data: json,
dataType: "jsonp",
}).success(function (json, status, headers, config) {
console.log(json);
})
};
// Creating a new instance on couchDB
$scope.submit = function () {
var entry = {
"Name": $scope.name,
"Comment": $scope.comment
};
console.log(entry);
var timestamp = Math.round(new Date().getTime() / 1000);
var url = 'https://sophia.iriscouch.com/guestbook/' + timestamp;
console.log(url);
$http({
url: url,
method: 'PUT',
data: entry,
dataType: "json",
withCredentials: true,
headers: {
'Authorization': auth_hash("sophia", "Einstein1")
}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {
console.log(headers);
console.log(config);
});
}
function auth_hash(username, password) {
var str = window.btoa(username + ":" + password);
return 'Basic' + str;
}
}]);
</script>
<form ng-controller="CouchController">
<p>
<input type="text" ng-model="comment">
</p>
<p>
<input type="text" ng-model="name">
</p>
<p>
<button ng-click="submit()">Add</button>
</p>
<p>
<button ng-click="view()">show</button>
</p>
</form>

you specify the dependent ngRoute module like
angular.module('guestBook', ['ngRoute'])
but you didn't add angular-route.js script file. adding that file will solve this.
here is the CDN of ngRoute module
after adding it the code should be like,
<div ng-app="guestBook">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular-route.js"></script>
....

Related

How to create service and use it in controller

I am having a simple login form and I want to validate user upon successful HTTP request and it works fine. however, I've written all the code in the controller itself and I don't want that. i am new to angularjs so i have trouble creating service. so I need to create service for my logic. can anyone create service for the logic in the controller so that code works exactly same?
sample.html(for now it only prints username, password, and status code of response)
<html>
<head>
<script src="angular.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="mycontroller">
Username <input type="text" ng-model="login" /><br><br> Password <input
type="password" ng-model="pass" /><br>
<button type="submit" ng-click="myfunc()">Login</button>
<center>User name is {{ login }}, password is{{pass}}<br>
{{success.code}}
</div>
</body>
</div>
</body>
</html>
Controller
var app = angular.module("myapp", []);
app.controller("mycontroller", function($scope, $http, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
$http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: mydata
}).then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});
Super simple. First create a service, which injects $http module. Make a method you can call which returns promise from the $http module. In this example it's a get method.
app.service("ExampleService", function($http){
this.ExampleRequest = function(){
return $http.get('url');
}
});
Inject the service created above and you can call the functions you've defined in the service. Notice that the .then comes from the promise.
app.controller("exampleCtrl", function($scope, ExampleService){
$scope.onClick = function(){
ExampleService.ExampleRequest().then(function(data){
// Do something with data
});
}
});
Create a myService factory and create a function to send http req and return the response.
app.factory('myService', function($http) {
return {
httpReq: function(data) {
return $http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: data
})
}
}
});
Now call it from the controller.
app.controller("mycontroller", function($scope, myService, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
myService.httpReq(mydata)
.then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});

angularjs data is not adding to service

I am using angularjs and ajax. I want to get the data from the webservice pass to controller. For passing the value to controller i am using holder (It's a factory method or service). It is working without webservice. But when i am calling data from web the data is getting correct but it is not updating to holder. My code is given below. When clicking the button "data1". I want to print the data from webservice in button name data2. It's not showing any error. And successfully data showing data in console but not adding data to holder.
index.html
<!DOCTYPE html>
<html ng-app="sharing">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ChildCtrl">
<button ng-click="increment() name="data1">+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2">
<h2>Second controller</h2>
<button ng-click="increment() name="data2">+</button>{{Holder.value}}
<button ng-click="" name="data3">+</button>{{Holder.name}}
</div>
</body>
</html>
script.js
// Code goes here
var app = angular.module('sharing', []);
var root="http://xxx.xxx.x.xx:60/Api";
app.factory('Holder', function() {
return {
value: 0,
name:""
};
});
app.controller('ChildCtrl', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
var jData1 = {};
jData1.BDMeetingId ="10003/2017";
var k=null;
console.log(JSON.stringify(jData1));
$.ajax({
type: "POST",
async: true,
url: root+"/Boardmeeting/BoardmeetingDetailsSevice",
data: JSON.stringify(jData1),
contentType: "text/plain",
dataType: "json",
crossDomain: true,
success: function (msg) {
k=msg;
$scope.BMNo=k.BMNo;
console.log(msg);
$scope.Holder.name=$scope.BMNo;
},
error: function (jqXHR, textStatus, errorThrown) {
},
});
};
});
app.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});
if you are using angularjs so please avoid to use jQuery code please remove $.ajax and use $http or $resource its angularjs inbuilt provider.
for more details.
https://docs.angularjs.org/api/ng/service/$http
https://docs.angularjs.org/api/ngResource/service/$resource
I have got the answer when using the angularjs webservice instead of ajax webservice.
script.js
var app = angular.module('sharing', []);
var root="http://xxx.xxx.x.xx:60/Api";
app.factory('Holder', function() {
return {
value: 0,
name:""
};
});
app.controller('ChildCtrl', function($scope, Holder, $http) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
var jData1 = {};
jData1.BDMeetingId ="10003/2017";
console.log(JSON.stringify(jData1));
$http({
method: 'POST',
url: root+"/Boardmeeting/BoardmeetingDetailsSevice",
headers: {
'Content-Type': 'text/plain', /*or whatever type is relevant */
'Accept': 'application/json' /* ditto */
},
data: JSON.stringify(jData1)
}).then(function(response) {
console.log(response);
var k=response;
$scope.BMNo=k.BMNo;
console.log(response.data.BMNo);
$scope.Holder.name=response.data.BMNo;
},
function(response) { // optional
// failed
});
};
});
app.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});

$http.post is sending as null in console as well as in url provided

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Struts 2 using AngularJS</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller("MyController",function($scope, $http) {
$scope.getDataFromServer = function() {
$http.get("angularAction").success(
function(data, status, headers, config) {
$scope.person = data;
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
$scope.postDataToServer=function(){
/*$scope.items={"firstName":"sandeep","lastName":"suluguri"}; */
/* var data = angular.toJson($scope.items); */
/* var data=$scope.items; */
In the console its printing as null and when i get the data from angularPage even its showing as null. Is my format of writing the post method correct?
$http({
method: 'POST',
url: 'angularPage',
data: {'message' : 'harsha'},
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}
}).success(function(data, status, headers, config) {
/* $scope.items = data; */
console.log(data);
}).error(function(data, status, headers, config) {
// alert("Error :: "+data);
console.log('error');
});
}
});
</script>
</head>
<body>
When I click the buttons it triggers the respective functions in the controllers.
My get method is working fine.It fetches data from that url and displays on the page
<div ng-app="myApp">
<div ng-controller="MyController">
<button ng-click="getDataFromServer()">
Fetch data from server
</button>
<p>First Name : {{person.firstName}}</p>
<p>Last Name : {{person.lastName}}</p>
<button ng-click="postDataToServer()">post data to server</button>
</div>
</div>
</body>
</html>

AngularJS "TypeError: Cannot read property 'protocol' of undefined" When get post data from web service

I'm trying to get data from web service. Here my code.
$scope.savePricing = function(){
var pricing = {
"PricingSchemeId": 0,
"Name": $scope.name,
"LastUserName": "Tan",
"LastModifiedDate": "",
"IsActive": true,
"CurrencyId": $scope.selectedCurrency.CurrencyId,
}
$http({
url: config.addPricing,
data: pricing,
method: "POST"
}).success(function(data){
alert("Success");
}).error(function(data){
alert("Failed");
});
})
But when i run this function, this error is shown:
What can i do now?
config.addPricing is undefined. I can easily reproduce that error as follows:
index.html:
<!DOCTYPE html>
<html ng-app="Foo">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="my-angular.js"></script>
</head>
<body ng-controller="SomeCtrl">
<button ng-click="go()">Go</button>
</body>
</html>
my-angular.js:
var app = angular.module("Foo", []);
app.controller("SomeCtrl", function($scope, $http) {
var config = {}; // Note the lack of "url" field.
$scope.go = function() {
$http({
url: config.url, // undefined
data: {},
method: "POST"
}).success(function(data) {
console.log("Success: data", data);
}).error(function(data) {
console.log("Error: data", data);
});
};
});

Can I change which JSON file is loaded by sending a variable to AngularJS?

I would like to load the content of one of two JSON files, food1.json or food2.json. I am trying to do this from the html template:
<body ng-controller="MainCtrl" ng-init="init('food1')">
And then in the JS:
$scope.init = function (name) {
$scope.name = name;
$scope.category = name + ".json";
$scope.foodlist = {};
$http({
method: 'GET',
url: $scope.category,
}).success(function (data, status, headers, config) {
{
$scope.foodlist = data;
}
}).error(function (data, status, headers, config) {
// something went wrong :(
});
};
});
The category name is properly assembled: I get "I am food1" if I print I am {{ category }}. But no food items are printed. I think I am doing the JSON call wrong.
Here's my Plunkr
You have not injected $http in the controller. Change you code as
app.controller('MainCtrl', function($scope, $http) {
instead of
app.controller('MainCtrl', function($scope) {
DEMO

Categories

Resources