Configure ngRoute with $http - angularjs

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.

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);
});
});
});

$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

Reduce the code redundancy in angularjs function

I am a calling function two time (I think which is not necessary) so how I can reduce the code so that my application performance will improve.
This is my code:
<!DOCTYPE html>
<html lang="en" ng-app="demo">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="jq.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<title>find freelancer..</title>
</head>
<body>
<div ng-controller="myCtrl">
Experence Level: <br>
Entry level:<input type="checkbox" ng-click="myClick()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<div ng-controller="myCtrl1">
Intermediate level:<input type="checkbox" ng-click="myClick1()">
<div ng-repeat="data in people">
{{data.sname}}
</div>
</div>
<script>
var app=angular.module('demo',[]);
app.controller('myCtrl',function($scope,$http)
{
$scope.myClick=function(event) {
$http.get("image.json")
.success(function(response){
$scope.people=response.jsonrecords;
});
}
});
app.controller('myCtrl1',function($scope,$http)
{
$scope.myClick1=function(event) {
$http.get("image.json")
.success(function(response){
$scope.people=response.jsonrecords;
});
}
});
</script>
</body>
</html>
As you are using same ajax request then it can be a proper candidate for making it a service/factory:
app.factory ('imgdata', ['$http', function(){
var result = $http.get('urlhere');
return result; // <--return it here.
});
Now imgdata can be injected:
app.controller('myCtrl',['$scope', 'imgdata', function($scope, imgdata){
$scope.myClick=function(event) {
imgdata.then(function (resp){
$scope.people = resp.data;
});
};
});
Same goes for other controller.
I think this is your target.. i hope helps you
var app = angular.module('demo', []);
app.controller('myCtrl', function($scope, appService) {
$scope.myClick = function(event) {
if ($scope.checkbox1) {
appService.get().success(function(response) {
//$scope.people = response;
});
} else {
$scope.people = [];
}
}
});
app.controller('myCtrl1', function($scope, appService) {
$scope.myClick1 = function(event) {
if ($scope.checkbox2) {
appService.get().success(function(response) {
//$scope.people = response;
});
} else {
$scope.people = [];
}
}
});
app.service("appService", function($http) {
this.get = function() {
return http({
url: "image.json",
method: "GET",
headers: {
'Content-Type': "application/json"
},
async: true
});
}
this.post = function() {
return http({
data: "////",
url: "url",
method: "POST",
headers: {
'Content-Type': "application/json"
},
async: true
});
}
//and .... edit .. delete
});
<!doctype html>
<html ng-app="demo">
<head>
</head>
<body>
<div ng-controller="myCtrl">
Entry level:
<input type="checkbox" ng-model="checkbox1" ng-change="myClick()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<div ng-controller="myCtrl1">
Intermediate level:
<input type="checkbox" ng-model="checkbox2" ng-change="myClick1()">
<div ng-repeat="data in people">
{{data.name}}
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
</body>
</html>
Depending on how you might use it later, but for the moment I would create a service looking a bit like this
app.factory('getPeople', function($http) {
return function($scope) {
return function(event) {
$http.get('image.json').success(function(response) {
$scope.people = response.jsonrecords;
});
};
};
});
Then your controller is dead simple
app.controller('myCtrl',function($scope, getPeople) {
$scope.myClick = getPeople($scope);
});

angular js not waiting for rest response

I am new to angular js. I have to work with the rest calls in java. I have taken an example related to angularjs, java rest.
see app.js
angular.module('ngdemo', ['ngRoute','ngdemo.filters', 'ngdemo.services', 'ngdemo.directives', 'ngdemo.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/user-list', {templateUrl: 'partials/user-list.html', controller: 'UserListCtrl'});
$routeProvider.when('/user-detail/:id', {templateUrl: 'partials/user-detail.html', controller: 'UserDetailCtrl'});
$routeProvider.when('/user-creation', {templateUrl: 'partials/user-creation.html', controller: 'UserCreationCtrl'});
}]);
controllers.js
'use strict';
/* Controllers */
var app = angular.module('ngdemo.controllers', []);
app.run(function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
});
app.controller('UserListCtrl', ['$scope', 'UsersFactory', 'UserFactory', 'DeleteUserFactory', 'UsersSearchFactory', '$location',
function ($scope, UsersFactory, UserFactory, DeleteUserFactory, UsersSearchFactory, $location) {
// callback for ng-click 'editUser':
$scope.editUser = function (userId) {
$location.path('/user-detail/' + userId);
};
$scope.searchUser = function () {
$scope.users = UsersSearchFactory.search($scope.user);
};
// callback for ng-click 'deleteUser':
$scope.deleteUser = function (user) {
DeleteUserFactory.delete(user);
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
};
// callback for ng-click 'createUser':
$scope.createNewUser = function () {
$location.path('/user-creation');
};
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
}]);
app.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserFactory', 'UpdateUserFactory', '$location',
function ($scope, $routeParams, UserFactory, UpdateUserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
UpdateUserFactory.update($scope.user);
$location.path('/user-list');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/user-list');
};
$scope.user = UserFactory.show({id: $routeParams.id});
}]);
app.controller('UserCreationCtrl', ['$scope', 'CreateUserFactory', '$location',
function ($scope, CreateUserFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user);
$location.path('/user-list');
}
}]);
services.js
'use strict';
/* Services */
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('UsersFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsers/:startRow/:endRow', {}, {
query: { method: 'GET', isArray: true, params: {startRow: '#startRow', endRow: '#endRow'} },
create: { method: 'POST' }
})
});
services.factory('UsersCountFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsersCount', {}, {
count: { method: 'GET'}
})
});
services.factory('UsersSearchFactory', function ($resource) {
return $resource('/ngdemo/rest/searchUser', {}, {
search: { method: 'POST', isArray: true, }
})
});
services.factory('CreateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/registerUser', {}, {
create: { method: 'POST' }
})
});
services.factory('UpdateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/updateUser', {}, {
update: { method: 'POST' }
})
});
services.factory('DeleteUserFactory', function ($resource) {
return $resource('/ngdemo/rest/deleteUser', {}, {
delete: { method: 'POST' }
})
});
services.factory('UserFactory', function ($resource) {
return $resource('/ngdemo/rest/findUserById/:id', {}, {
show: { method: 'GET' }
})
});
user-list.html
<div class="container">
<form novalidate="novalidate" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputFirstName">First name:</label>
<div class="controls">
<input type="text" id="inputFirstName" ng-model="user.firstName" placeholder="First name"/>
</div>
</div>
<div class="form-group">
<div class="controls">
<a ng-click="searchUser()" class="btn btn-primary btn-xs">Search</a>
</div>
</div>
</form>
</div>
<div class="span6">
<table class="table table-striped table-condensed" >
<thead>
<tr>
<th style="min-width: 80px;"> First Name</th>
<th style="min-width: 80px;"> Last Name</th>
<th style="width:20px;"> </th>
<th style="width:20px;"> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" > <!-- | orderBy:sort.sortingOrder:sort.reverse" > -->
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td><a ng-click="editUser(user.userId)" class="btn btn-small btn-primary">edit</a></td>
<td><a ng-click="deleteUser(user)" class="btn btn-small btn-danger">delete</a></td>
</tr>
</tbody>
</table>
<a ng-click="createNewUser()" class="btn btn-small">create new user</a>
</div>
index.html
<!doctype html>
<html lang="en" ng-app="ngdemo">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ngdemo app</title>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
</head>
<body>
<ul class="menu">
<li>user-list</li>
</ul>
<div ng-view></div>
<!-- JQuery ================================================================ -->
<script src="js/jquery/jquery-2.0.3.js"></script>
<!-- Bootstrap ============================================================= -->
<script src="js/bootstrap/bootstrap.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.js"></script>
<!-- AngularJS App Code ==================================================== -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
Question:
I am getting the rest call to server and it is sending the response.
When i open index.html it is displaying the out put on the page. When i click on edit(update) or delete buttons or create new user button, the user details are saved in the database but the changed data is not displayed on the table.
This is happened because after editing(updating) , deleting and creating new user the angular code is not waiting for the response from REST call. It immediately calls the $location.path('/user-list'); So old data is displayed in the table.
Please help me.
I have added the success call backs for all the methods update, create, delete as
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user, function(response) {
$location.path('/user-list');
});
}

Angularjs modal window with routeProvider

I'm having trouble using routeProvider to display a modal window. I am displaying a table list of ingredients and hoping that by clicking on an ingredient, I can display an "update" modal. The table displays properly and I can even view a single ingredient outside of a modal context but as soon as I try and get the modal working everything falls apart - in fact, the modal doesn't even properly receive its "ingredient" variable. When clicking on a table row the HTML for the modal is displayed like it's a separate page.
app.js:
angular.module('IngredientsApp', [
'IngredientsApp.controllers',
'IngredientsApp.services',
'ngRoute',
'ui.bootstrap'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/ingredients", {templateUrl: "partials/ingredients.html", controller: "ingredientsController"}).
when("/ingredient/:id", {templateUrl: "partials/ingredient.html", controller: "ingredientController"}).
otherwise({redirectTo: '/ingredients'});
}]);
services.js:
angular.module('IngredientsApp.services', []).factory('ingredientAPIservice', function($http) {
var ingredientAPI = {};
ingredientAPI.getIngredients = function() {
return $http.get('/ingredient');
}
ingredientAPI.getIngredient = function(id) {
return $http.get('/ingredient/'+id+'/edit');
}
return ingredientAPI;
});
index.html
<!doctype html>
<html lang="en">
<head>
<title>Our Recipes</title>
<script type="text/javascript" src="/js/angular.min.js"></script>
<script type="text/javascript" src="/js/angular-route.min.js"></script>
<script type="text/javascript" src="/js/angular-bootstrap.min.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript" src="/js/services.js"></script>
<script type="text/javascript" src="/js/controllers.js"></script>
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
</head>
<body ng-app="IngredientsApp">
<ng-view></ng-view>
</body>
</html>
ingredients.html
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Existing Ingredients</th>
<th><input type="text" ng-model="descriptionFilter" placeholder="Search..."/></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in ingredientsList | filter: searchFilter">
<td>
<a href="/#/ingredient/{{i.Id}}">
{{i.Description}}
</a>
</td>
<td>Created at {{i.CreatedAt}}</td>
</tr>
</tbody>
</table>
ingredient.html
<script type="text/ng-template">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
{{ingredient.Description}}
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Dismiss</button>
</div>
</script>
controllers.js:
angular.module('IngredientsApp.controllers', []).controller('ingredientsController', function($scope, ingredientAPIservice) {
$scope.descriptionFilter = null;
$scope.ingredientsList = [];
$scope.searchFilter = function (ingredient) {
var keyword = new RegExp($scope.descriptionFilter, 'i');
return !$scope.descriptionFilter || keyword.test(ingredient.Description);
};
ingredientAPIservice.getIngredients().success(function (response) {
//Dig into the responde to get the relevant data
$scope.ingredientsList = response;
});
})
var ingredientController = function($scope, $routeParams, $modal, ingredientAPIservice) {
$scope.id = $routeParams.id;
$scope.ingredient = null;
ingredientAPIservice.getIngredient($scope.id).success(function (response) {
$scope.ingredient = response;
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'partials/ingredient.html',
controller: 'ingredientModalController',
size: size,
resolve: {
ingredient: function () {
console.log($scope.ingredient);
return $scope.ingredient;
}
}
});
}
});
}
var ingredientModalController = function($scope, $modalInstance, ingredient) {
$scope.ingredient = ingredient;
$scope.ok = function () {
$modalInstance.close($scope.ingredient);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
I believe your issue is in app.js. Your route change causes the modal template (partials/ingredients.html) to be the only template displayed in ui-view. For the modal to work, you need to have the ingredients template nested within the ingredient template so both templates can be displayed at the same time. There are multiple ways to accomplish this.
If you are willing to give up the route change, just remove
when("/ingredient/:id", {templateUrl: "partials/ingredient.html", controller: "ingredientController"})
If you need the url to change, then I would look at doing it manually through the build in location service. https://docs.angularjs.org/guide/$location
You could just call a function that changes the url on click of an ingredient.

Resources