ng-include not working for basic angular 1 code - angularjs

Ok, there're many similar questions, i went through some and get me more confused, btw i started learning angular 1 about 2 weeks ago.
in browser, /mypath/status.html works fine, it sends "testJson" to node server, then
displays data to the webpage
now i have /mypath/index2.html, which ng-include status.html, it won't
trigger "testJson" in the server code
status.html
<!DOCTYPE html>
<html ng-app="HelloModule">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
</head>
<body ng-controller="HelloCtrl">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/
angular.js"></script>
<script src="statusApp.js"></script>
<table>
<tr>
<th>Code</th>
<th>Country</th>
<th>Population</th>
</tr>
<tr ng-repeat="country in countries | orderBy: 'code' ">
<th>{{country.code}}</th>
<th>{{country.name}}</th>
<th>{{country.population}}</th>
</tr>
</table>
</body>
</html>
statusApp.js
var app = angular.module('HelloModule', []);
app.controller('HelloCtrl', function($scope, HelloService) {
//$scope.countries = [{code : "US", name : "United States", population : "11223344"}];
HelloService.getJson().then(function(result) {
$scope.countries = result;
}, function(error) {
alert("Error");
} );
});
app.factory('HelloService', function($http, $q) {
return {
getJson: function() {
var deferred = $q.defer();
var browserProtocol = 'http';
var port = ':1234';
var address = 'localhost';
var server = browserProtocol + '://' + address;
var url = server + port + '/testJson';
//$http.get('http://localhost:7778/testJson').success(function(data) {
$http.get(url).success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
}
});
index2.html which is not working,
i don't see this line
console.log("returning Json data");
triggered in the server
<!DOCTYPE html>
<html ng-app>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.
min.js"></script>
<div class="container">
<div ng-include="" src="'status.html'"></div>
</div>
</body>
</html>
server side
app.get('/testJson', function(req, res)
{
console.log("returning Json data");
res.json( [{code : "US", name : "United States", population : "11223344"
}] );
});

The status.html that you want to include is :
<table ng-controller="HelloCtrl" >
<tr>
<th>Code</th>
<th>Country</th>
<th>Population</th>
</tr>
<tr ng-repeat="country in countries | orderBy: 'code' ">
<th>{{country.code}}</th>
<th>{{country.name}}</th>
<th>{{country.population}}</th>
</tr>
</table>
Right ?
EDIT
And ng-include works like this :
<div class="container">
<div ng-include="'status.html'" ></div>
</div>

Related

Angular JS expression not evaluating using $http service

This is Script.js
var app = angular
.module("myModule", [])
.controller("myController", function ($scope, $http) {
$http.get(
url: 'EmployeeService.asmx/GetAllEmployees'
)
.then(function (response) {
$scope.employees = response.data;
});
});
This is Htmlpage1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<script src="Scripts/Script.js"></script>
</head>
<body ng-app="myModule">
<div ng-controller="myController">
<table border="1" style="border:none;">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees">
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.salary}}</td>
</tr>
</tbody>
</table>
</div>
</html>
The expression Id Name Gender Salary
{{employee.id}} {{employee.name}} {{employee.gender}} {{employee.salary}} is not getting evaluated
The values of the table are not displaying
$http.get() method gets the url parameter as a string, so you are not using it correctly. This is the correct syntax:
$http.get('EmployeeService.asmx/GetAllEmployees')
Read more: $http#get
IF the url is correct then your code should work with this change
What event or who is making that request?
var app = angular
.module("myModule", [])
.controller("myController", function ($scope, $http) {
//when the page is ready
angular.element(document).ready(function() {
$http({ method: 'GET',
url: 'EmployeeService.asmx/GetAllEmployees'
}).then(function (response) {
$scope.employees = response.data;
}).catch(function (err) {
console.log('Error encountered : ' + err);
});
});
});

Display JSON response with Angularjs

I need to display data from JSON response using Angularjs
When checking the response with DevTools i can see the results, but when it comes to diplay, it doesn't work
Controller :
MovieApp.controller('movieAdminCtrl', ['$http', '$scope', function($http, $scope){
$scope.movies=[];
$http.get('http://localhost:3000/movies').success(function(data) {
$scope.movies = data;
});
}]);
Response :
Display Code :
<tbody ng-repeat="movie in movies" >
<td></td>
<td >{{movie.title}}</td>
<td >{{movie.actors}}</td>
<td >{{movie.Created_date}}</td>
<td><img ng-src="{{movie.poster}}" /></td>
You need to access the data property of the response
$http.get('http://localhost:3000/movies').success(function(data) {
$scope.movies = data.data;
});
Please try this code..
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body ng-app="app" ng-controller="movieAdminCtrl">
<table>
<tr ng-repeat="movie in movies">
<td></td>
<td>{{movie.title}}</td>
<td>{{movie.actors}}</td>
<td>{{movie.Created_date}}</td>
<td>
<img ng-src="{{movie.poster}}" />
</td>
</tr>
</table>
<script src="../lib/angular.js"></script>
<script>
var MovieApp = angular.module('app', []);
MovieApp.controller('movieAdminCtrl', ['$http', '$scope', function ($http, $scope) {
$scope.movies = [];
$http.get('http://localhost:3000/movies').success(function (data) {
$scope.movies = data;
});
}]);
</script>
</body>
</html>

$http.delete returns error 404

I am new to Angular and I'm trying to build a CRUD using the MEAN stack.
Yet I am having trouble with Angular to call the DELETE function on the server side.
Here is my Angular App.JS
var app = angular.module('topshelf', [])
app.controller('MainCtrl', [
'$scope','$http',
function($scope , $http){
var Mydata = {};
$http.get("http://localhost:8080/inventory").success(function(data,status,header,config){
$scope.Mydata = data;
});
$scope.delete = function($index) {
var url = "http://localhost:8080/ingredients/" + $index;
$http.delete(url).success(function(err,data){
if (err){ console.log(err);}
$scope.Mydata = data;
console.log("test");
});
}
}]);
and here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TopShelf</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="./app.js"></script>
</head>
<body ng-app ="topshelf" ng-controller="MainCtrl" class="top-navigation">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Ingredient</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ingredients in Mydata">
<td>{{ingredients.name}} </td>
<td>{{ingredients.quantity}} </td>
<td> Add / Edit / <a ng-click="delete($index)">Delete</a></form></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
UPDATE
Also, here is my server code specifying the routes though when I try the routes with POSTMAN it works fine.:
var express = require('express');
var Ingredients = require('./models/ingredients.js');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/labelleassiette');
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
res.sendFile(__dirname+"/public/index.html");
})
app.get('/inventory',function(req,res){
Ingredients.find(function(err,ingr){
res.json(ingr);
})
})
app.post('/add', function(req,res){
var entry = new Ingredients({name: req.body.name, quantity: req.body.quantity});
var self = this;
Ingredients.find({name:req.body.name}, function(err,data){
if(data.length){
res.send(500,"Ingredient exists!");
}
else{
entry.save(function(err){
if (err) {console.log(err);}
else { console.log('Saved to db')}
});
res.redirect('/');
}
})
})
app.put('/ingredients/:id',function(req,res) {
var id = req.params.id;
var obj = req.body;
Ingredients.findByIdAndUpdate(id, {name: obj.name, quantity: obj.quantity}, function(err){
if (err) {console.log(err);}
console.log("updated");
})
})
app.delete('/ingredients/:id',function(req,res){
Ingredients.findByIdAndRemove(req.params.id,function(err){
if (err) {console.log(err);}
console.log("effacé");
res.redirect('/');
})
})
app.listen(8080, function() {
console.log("listening on port 8080!");
});
i am getting a DELETE http://localhost:8080 404 not found on my browser's console.
Thank you guys for your help

Configure ngRoute with $http

I am trying to confugure ngRoute with $http and I am getting error in console when i go to website: localhost:8080
Uncaught ReferenceError: angularModule is not defined(anonymous
function) # item_controller.js:2
angular.js:38Uncaught Error:
[$injector:modulerr]
http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=myApp&p1=Error%3A%2…2Flocalhost%3A8080%2Fbower_components%2Fangular%2Fangular.min.js%3A21%3A19)
When I open http://localhost:8080/home then I see "Whitable error page". I am writeing my API in Spring framework (Spring-boot)
How should I configure these two things to work properly? I cant find any good example how should i write this in good way.
My configuration looks like below:
app.js
'use strict';
var App = angular.module('myApp', ['ngRoute', 'moduleItemController']);
App.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when( '/home', {
templateUrl: '../item.html',
controller: 'ItemController'
}).
when('/item/:itemCode',{
templateUrl: '../../templates/item-detail.html',
controller: 'ItemController'
}).otherwise({
redirectTo: '/home'
});
}]);
item_controller.js
'use strict';
var moduleItemController = angularModule.module('moduleItemController',[])
moduleItemController.controller('ItemController', ['$scope', 'ItemService', function ($scope, ItemService) {
var self = this;
self.item = {id: null, itemCode: '', itemName: '', price: ''};
self.items = [];
self.fetchAllItems = function () {
ItemService.fetchAllItems()
.then(
function (d) {
self.items = d;
},
function (errResponse) {
console.error('Error while fetching Currencies');
}
);
};
self.createItem = function (item) {
ItemService.createItem(item)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while creating item.');
}
);
};
self.updateItem = function (item, id) {
ItemService.updateItem(item, id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while updating item.');
}
);
};
self.deleteItem = function (id) {
ItemService.deleteItem(id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while deleting item.');
}
);
};
self.updatePrice = function (newPrice, item, id) {
ItemService.updatePrice(newPrice, item, id)
.then(
self.fetchAllItems,
function (errResponse) {
console.error('Error while updating item.');
}
);
};
self.fetchAllItems();
self.submit = function () {
if (self.item.id === null) {
console.log('Saving New item', self.item);
self.createItem(self.item);
}
else {
console.log('Sth went wrong!');
}
self.reset();
};
self.remove = function (id) {
console.log('id to be deleted', id);
if (self.item.id === id) {
self.reset();
}
self.deleteItem(id);
};
self.reset = function () {
self.item = {id: null, itemCode: '', itemName: '', price: ''};
$scope.myForm.$setPristine();
};
}]);
moduleItemController.controller('ItemController', ['$scope','$routeParams', function ($scope,$routeParams) {
$scope.itemCode = $routeParams.itemCode;
}]);
item_service.js
App.factory('ItemService', ['$http', '$q', function ($http, $q) {
return {
fetchAllItems: function () {
return $http.get('http://localhost:8080/api/item/all')
.then(
function (response) {
return response.data;
console.success('Success');
},
function (errResponse) {
console.error('Error while fetching users');
return $q.reject(errResponse);
}
);
},
.
.
.
// other crud operations
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HOME</title>
<link rel="stylesheet" type="text/css" href="bower_components/semantic/dist/semantic.min.css">
<script src="bower_components/semantic/dist/semantic.js"></script>
<!--Angular dependencies-->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controller/item_controller.js"></script>
<script src="js/service/item_service.js"></script>
</head>
<body ng-app="myApp">
<div ng-view></div>
</body>
</html>
item.html -- here is part of this file where I want to use ngRoute
<table class="ui fixed table">
<thead>
<tr>
<th>Id</th>
<th>Code</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th width="20%"></th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in ictrl.items | filter:query">
<td><span ng-bind="i.id"></span></td>
<td class="selectable">
<span ng-bind="i.itemCode"></span>
</td>
<td><span ng-bind="i.itemName"></span></td>
<td><span ng-bind="i.price"></span></td>
<td><span ng-bind="i.quantity"></span></td>
<td>
<button class="negative ui button" ng-click="ictrl.remove(i.id)">delete</button>
</td>
<td>
<button class="ui secondary button">zp</button>
</td>
</tr>
</tbody>
</table>
item-detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Details</title>
<!--SEMANTIC-->
<link rel="stylesheet" type="text/css" href="bower_components/semantic/dist/semantic.min.css">
<script src="bower_components/semantic/dist/semantic.js"></script>
<!--ANGULAR-->
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/angular-route/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controller/item_controller.js"></script>
<script src="js/service/item_service.js"></script>
</head>
<body ng-app="myApp">
<div class="item table container">
<h1>TBD DETAILED VIEW FOR {{itemCode}}</h1>
</div>
</body>
</html>
The problem is you are trying to use angularModule instead of angular in item_controller.js. The global object from angular.js is angular and not angularModule
Change the below line as:
var moduleItemController = angularModule.module('moduleItemController',[]);
to
var moduleItemController = angular.module('moduleItemController',[]);
Line 2 of item_controller.js is referencing angularModule.module which is undefined. I think you want angular.module.

Single or Multiple Model InJecting using service directive in seperate javascript file in angularJs

When i am trying to inject single or multiple model using service directive in separate java script file , i am getting below error,But it si working in single Javascript files. Here customer is model
Error:
"Binding.js:33 Uncaught ReferenceError: Customer is not defined".
Binding.js:9 Uncaught ReferenceError: Customer is not defined(anonymous function) # Binding.js:9
angular.js:13424 Error: [$injector:unpr] Unknown provider: customerProvider <- customer <- myCustomerController
Below is my code :
Model(customer.js) :
function Customer() {
this.customerName = "David";
this.customerCode = "C001";
}
Binding Code(Binding.js)
function BindingCode($scope,customer) {
$scope.customer = customer;
}
var myCustomerApp = angular.module("myCustomerApp", []);
myCustomerApp.controller("myCustomerController", BindingCode);
myCustomerApp.service('customer', Customer);
View Code(customer.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/Binding.js"></script>
</head>
<body ng-app="myCustomerApp">
<div ng-controller="myCustomerController">
<table>
<tr>
<td>
CustomerName
</td>
<td>
<input type=text id="CustomerName" ng-model="customer.customerName" /><br />
</td>
</tr>
<tr>
<td>
CustomerCode
</td>
<td>
<input type=text id="CustomerCode" ng-model="customer.customerCode" />
</td>
</tr>
</table>
</div>
But Same code is working here only model and view and binding code included in section script in customer.html:
Model :Customer.js
function Customer() {
this.customerName = "David";
this.customerCode = "C001";
}
View code (customer.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/CustomerModle.js"></script>
</head>
<script>
function BindingCode($scope, customer) {
$scope.customer = customer;
}
var myCustomerApp = angular.module("myCustomerApp", []);
myCustomerApp.controller("myCustomerController", BindingCode);
myCustomerApp.service('customer', Customer);
</script>
<body ng-app="myCustomerApp">
<div ng-controller="myCustomerController">
</div>
</body>
</html>
You should first inject the service into your controller before yousing that service.
BindingCode.$inject = ['Customer']
Re-arrange the customer.js into
var myCustomerApp = angular.module("myCustomerApp", []);
myCustomerApp.service('customer', Customer);
function Customer() {
this.customerName = "David";
this.customerCode = "C001";
}
Rearrange the Binding.js into
var myCustomerApp = angular.module("myCustomerApp", []);
myCustomerApp.controller("myCustomerController", BindingCode);
BindingCode.$inject = ['Customer']
function BindingCode($scope,Customer) {
$scope.customer = Customer;
}
add <script src="Scripts/customer.js"></script> in your customer.html file

Resources