angular.js ReferenceError: $document is not defined - angularjs

Hi I am getting at console :
angular.js:10072ReferenceError: $document is not defined
at link (http://localhost:9999/CheckBoxOperation/:173:15)
at N
<table class="table table-bordered" arrow-selector="">
Actually I am trying to do arrow selection like this http://code.ciphertrick.com/2015/03/15/change-row-selection-using-arrows-in-ng-repeat/
I am getting that error because of code which is inside dashed line in my code. I think it is related to script but I didn't get.
This is my code:
AngularJS check box
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http)
{
$scope.headerText = ' Form';
$scope.selectedColor;
$scope.Levels=[]; //for checkbox name
$scope.Rows=[]; //for rows
$scope.selection=[];
$scope.selectedRow=0;
$http({method: 'GET', url: 'controller/getLevelCheckBox'}).
success(function(data, status, headers, config)
{
angular.forEach(data, function(value, key)
{
$scope.Levels.push(value);
});
})
// toggle selection for a given level by name
$scope.toggleSelection = function toggleSelection(levelName) {
var idx = $scope.selection.indexOf(levelName);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(levelName);
$scope.getAllJobs = function()
{
var response = $http.get('controller/getDataTable/'+levelName);
response.success(function(data, status, headers, config)
{
angular.forEach(data, function(value, key)
{
$scope.Rows.push(value); //json Array valuessss
});
$scope.setClickedRow = function(index){
// window.alert("row clicked "+index);
$scope.selectedRow = index;
}
$scope.$watch('selectedRow', function() {
console.log('Do Some processing'); //runs the block whenever selectedRow is changed.
});
window.alert("sccusee");
});
response.error(function(data, status, headers, config)
{
alert("staus ::"+status);
});
}//getAllJobs()
}//else
};//toggle function
}]);//controller
app.directive('arrowSelector',function(){
return{
restrict:'A',
link:function(scope,elem,attrs,ctrl){
var elemFocus = false;
elem.on('mouseenter',function(){
elemFocus = true;
console.log(true);
});
elem.on('mouseleave',function(){
elemFocus = false;
console.log(false);
});
//--------------------------------------------------------------
$document.bind('keydown',function(e){
console.log("bind");
if(elemFocus){
if(e.keyCode == 38){
console.log(" 38 kjeeeey ::"+scope.selectedRow);
if(scope.selectedRow == 0){
return;
}
scope.selectedRow--;
scope.$apply();
e.preventDefault();
}
if(e.keyCode == 40){
if(scope.selectedRow == scope.Rows.length - 1){ return;
}
scope.selectedRow++;
scope.$apply();
e.preventDefault();
}
}
}); //till this point
}
};
});
</script>
</head>
<body data-ng-controller="FormSubmitController">
<h3>{{headerText}}</h3>
<div class=panel>
<div class="check-box-panel">
<div data-ng-repeat="level in Levels">
<div class="action-checkbox">
<input id="{{level}}" type="checkbox" value="{{level}}" data-ng-checked="selection.indexOf(level) > -1"
data-ng-click="toggleSelection(level)" />
<label for="{{level}}"></label>
{{level}}
</div>
</div>
<input type="submit" value="show all jobs " data-ng-click="get All Jobs()"/>
</div>
<div class="selected-items-panel">
<table class="table table-bordered" arrow-selector>
<thead>
<tr data-ng-repeat="(key,value) in Rows" data-ng-if="$last">
<td data-ng-repeat="(key,v) in value"><input type="button" value={{key}}></td>
</tr>
<tbody>
<tr data-ng-class="{'selected':$index == selectedRow}" data-ng-click="setClickedRow($index)"
data-ng-repeat="(key,value) in Rows">
<td data-ng-repeat="(key,v) in value">{{v}}</td>
</tr>
</tbody>
</table>
<div>
selectedRow = {{selectedRow}}
</div>
<div>
item = {{Rows[selectedRow]}}
</div>
</div>
</div>
</body>
</html>

You can use angular.element(document) to get the jquery equivalent

Related

angular service sample not working

I am following a tutorial for angular and a bit stuck with service.
here is the plunk where I am stuck.
it runs into issue when injecting the parameters for consrtuctor.
Can someone please have a quick look?
plunk here
https://plnkr.co/edit/rMKt3h?p=preview
related code as follows
github.js --service code
(function() {
var github = function($http) {
var getUser = function(username) {
return $http.get('https://api.github.com/users/' + username)
.then(function(response) {
return response.data;
});
};
var getRepos = function(user) {
return $http.get(user.repos_url)
.then(function(response) {
return response.data;
});
};
return {
getUser: getUser,
getRepos:getRepos
};
};
var module = angular.module("gitHubViewer");
module.factory("github", github);
}());
index.html
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css">
<script src="lib/script.js"></script>
<script src="github.js"></script>
</head>
<body ng-app="gitHubViewer" ng-cloak>
<div ng-controller="EmployeeController">
<div ng-show="error">{{error}}</div>
{{countDown}}
<h2>{{user.name}}</h2>
<form name="searchUser" ng-submit="search(username)">
<input type="search" required ng-model="username" />
<input type="submit" value="Search" />
</form>
{{username}}
<select ng-model="repoSortOrder">
<option value="name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="language">Language</option>
</select>
<!--<div>
<img ng-src="{{user.avatar_url}}" />
</div>-->
<table style="border:1">
<thead>
<tr>
<th>Name</th>
<th>stargazers_count</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | orderBy:repoSortOrder">
<td>
{{repo.name}}
</td>
<td>
{{repo.stargazers_count | number:2}}
</td>
<td>
{{repo.language}}
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
script.js
import angular from 'angular';
(function() {
var app = angular.module('gitHubViewer', []);
var EmployeeController = function($scope,github, $interval,$log) {
$scope.search = function(username) {
$scope.error = null;
$log.info("Searching for user : " + username);
//gitHubService.getUser(username)
// .then(onResponse, onError);
//$http.get('https://api.github.com/users/' + username)
// .then(onResponse, onError);
github.getUser(username)
.then(onResponse, onError);
if(countDownInterval!==null)
{
$interval.cancel(countDownInterval);
$scope.countDown=null;
}
};
var onResponse = function(data) {
$scope.user = data;
//$http.get($scope.user.repos_url)
// .then(onReposResponse, onError);
github.getRepos(data)
.then(onReposResponse,onError);
};
var onReposResponse = function(data) {
$scope.repos = data;
};
var onError = function(error) {
$scope.error = error;
};
var decrementCountDown = function() {
$scope.countDown -= 1;
if ($scope.countDown < 1) {
$scope.search($scope.username);
}
};
var countDownInterval = null;
var startCountDown = function() {
countDownInterval = $interval(decrementCountDown, 1000, 5);
};
$scope.username = "Angular";
$scope.message = "github viewer";
$scope.repoSortOrder = "-stargazers_count";
$scope.countDown = 5;
startCountDown();
};
app.controller("EmployeeController", ["$scope","github", "$interval","$log", EmployeeController]);
}());
It might be because of the order of the JS files listed in the HTML:
<script src="lib/script.js"></script>
<script src="github.js"></script>
Since var github is used in script.js, and it's defined in github.js, github.js should come first then script.js. Like this:
<script src="github.js"></script>
<script src="lib/script.js"></script>
I had a similar issue with Bootstrap and jQuery UI.

Error: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector

This is the first time I have asked a question which I really need an answer to. I'm hoping you folks will generously share some of your answers and insights.
I've been trying to replicate the JavaScript Projects list tutorial on the angularjs.org homepage (the third tutorial from the top of the homepage) in which they have a list which you can add or delete items from, the heading for this tutorial is called 'Wire Up a Backend.'
Well, i replicated the lines of code for all of it, line for line, and it does not look like the tutorial's finished product at all. Upon closer inspection, the console logs an error about injection dependencies.
The code was the same line by line, but it still did not work.
Here is the code:
index.html:
<!doctype html>
<html ng-app="project">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.min.js">
</script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
projects.js:
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://ng-projects-list.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth, projectListValue) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(projectListValue);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
//Remove projects list when no longer needed.
ref.onDisconnect().remove();
return deferred.promise;
});
};
})
.config(function($routeProvider) {
var resolveProjects = {
projects: function (Projects) {
return Projects.fetch();
}
};
$routeProvider
.when('/', {
controller:'ProjectListController as projectList',
templateUrl:'list.html',
resolve: resolveProjects
})
.when('/edit/:projectId', {
controller:'EditProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.when('/new', {
controller:'NewProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.otherwise({
redirectTo:'/'
});
})
.controller('ProjectListController', function(projects) {
var projectList = this;
projectList.projects = projects;
})
.controller('NewProjectController', function($location, projects) {
var editProject = this;
editProject.save = function() {
projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditProjectController',
function($location, $routeParams, projects) {
var editProject = this;
var projectId = $routeParams.projectId,
projectIndex;
editProject.projects = projects;
projectIndex = editProject.projects.$indexFor(projectId);
editProject.project = editProject.projects[projectIndex];
editProject.destroy = function() {
editProject.projects.$remove(editProject.project).then(function(data) {
$location.path('/');
});
};
editProject.save = function() {
editProject.projects.$save(editProject.project).then(function(data) {
$location.path('/');
});
};
});
list.html:
<input type="text" ng-model="projectList.search" class="search-query" id="projects_search"
placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projectList.projects | filter:projectList.search | orderBy:'name'">
<td><a ng-href="{{project.site}}" target="_blank">{{project.name}}</a></td>
<td>{{project.description}}</td>
<td>
<a ng-href="#/edit/{{project.$id}}"><i class="icon-pencil"></i></a>
</td>
</tr>
</tbody>
</table>
detail.html:
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid && !myForm.name.$pristine}">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name" required>
<span ng-show="myForm.name.$error.required && !myForm.name.$pristine" class="help-inline">
Required {{myForm.name.$pristine}}</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid && !myForm.site.$pristine}">
<label>Website</label>
<input type="url" name="site" ng-model="editProject.project.site" required>
<span ng-show="myForm.site.$error.required && !myForm.site.$pristine" class="help-inline">
Required</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="editProject.project.description"></textarea>
<br>
Cancel
<button ng-click="editProject.save()" ng-disabled="myForm.$invalid"
class="btn btn-primary">Save</button>
<button ng-click="editProject.destroy()"
ng-show="editProject.project.$id" class="btn btn-danger">Delete</button>
</form>
This is the error that shows up on the console: [$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=projectListValueProvider%20%3C-%20projectListValue%20%3C-%20Projects
Please help, I know there are a lot of you that are much more experienced, and I certainly hope I find some answers because I don't have much to turn to, and I've been trying to figure this out for the past couple of days now, so humbly request the help of you veteran coders, and wise sages of the stackoverflow realm.
You're attempting to inject projectListValue into your Projects service. You never actually define and inject projectListValue, and it's breaking when it attempts to get it.
--
The following gets rid of the error, by getting rid of the injection.
.service('Projects', function($q, $firebase, fbRef, fbAuth) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
//Remove projects list when no longer needed.
ref.onDisconnect().remove();
return deferred.promise;
});
};
})

AngularJS Wire up a Backend c/p from site not working

i'm trying to get this example working in Visual Studio 2015. I've created empty project and c/p files from site and for some reason i'm getting following error:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.3/$injector/modulerr?p0=project&p1=Error%3A…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.3%2Fangular.min.js%3A39%3A135)
I've googled a bit around and saw similar problems with version 1.2.x, suggested fix is not working. What am i missing?
project.js
angular.module('project', ['ngRoute', 'firebase'])
.value('fbURL', 'https://ng-projects-list.firebaseio.com/')
.service('fbRef', function(fbURL) {
return new Firebase(fbURL)
})
.service('fbAuth', function($q, $firebase, $firebaseAuth, fbRef) {
var auth;
return function () {
if (auth) return $q.when(auth);
var authObj = $firebaseAuth(fbRef);
if (authObj.$getAuth()) {
return $q.when(auth = authObj.$getAuth());
}
var deferred = $q.defer();
authObj.$authAnonymously().then(function(authData) {
auth = authData;
deferred.resolve(authData);
});
return deferred.promise;
}
})
.service('Projects', function($q, $firebase, fbRef, fbAuth, projectListValue) {
var self = this;
this.fetch = function () {
if (this.projects) return $q.when(this.projects);
return fbAuth().then(function(auth) {
var deferred = $q.defer();
var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
var $projects = $firebase(ref);
ref.on('value', function(snapshot) {
if (snapshot.val() === null) {
$projects.$set(projectListValue);
}
self.projects = $projects.$asArray();
deferred.resolve(self.projects);
});
//Remove projects list when no longer needed.
ref.onDisconnect().remove();
return deferred.promise;
});
};
})
.config(function($routeProvider) {
var resolveProjects = {
projects: function (Projects) {
return Projects.fetch();
}
};
$routeProvider
.when('/', {
controller:'ProjectListController as projectList',
templateUrl:'list.html',
resolve: resolveProjects
})
.when('/edit/:projectId', {
controller:'EditProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.when('/new', {
controller:'NewProjectController as editProject',
templateUrl:'detail.html',
resolve: resolveProjects
})
.otherwise({
redirectTo:'/'
});
})
.controller('ProjectListController', function(projects) {
var projectList = this;
projectList.projects = projects;
})
.controller('NewProjectController', function($location, projects) {
var editProject = this;
editProject.save = function() {
projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
})
.controller('EditProjectController',
function($location, $routeParams, projects) {
var editProject = this;
var projectId = $routeParams.projectId,
projectIndex;
editProject.projects = projects;
projectIndex = editProject.projects.$indexFor(projectId);
editProject.project = editProject.projects[projectIndex];
editProject.destroy = function() {
editProject.projects.$remove(editProject.project).then(function(data) {
$location.path('/');
});
};
editProject.save = function() {
editProject.projects.$save(editProject.project).then(function(data) {
$location.path('/');
});
};
});
index.html
<!doctype html>
<html ng-app="project">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-resource.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="project.js"></script>
</head>
<body>
<h2>JavaScript Projects</h2>
<div ng-view></div>
</body>
</html>
list.html
<input type="text" ng-model="projectList.search" class="search-query" id="projects_search"
placeholder="Search">
<table>
<thead>
<tr>
<th>Project</th>
<th>Description</th>
<th><i class="icon-plus-sign"></i></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="project in projectList.projects | filter:projectList.search | orderBy:'name'">
<td><a ng-href="{{project.site}}" target="_blank">{{project.name}}</a></td>
<td>{{project.description}}</td>
<td>
<a ng-href="#/edit/{{project.$id}}"><i class="icon-pencil"></i></a>
</td>
</tr>
</tbody>
</table>
detail.html
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid && !myForm.name.$pristine}">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name" required>
<span ng-show="myForm.name.$error.required && !myForm.name.$pristine" class="help-inline">
Required {{myForm.name.$pristine}}
</span>
</div>
<div class="control-group" ng-class="{error: myForm.site.$invalid && !myForm.site.$pristine}">
<label>Website</label>
<input type="url" name="site" ng-model="editProject.project.site" required>
<span ng-show="myForm.site.$error.required && !myForm.site.$pristine" class="help-inline">
Required
</span>
<span ng-show="myForm.site.$error.url" class="help-inline">
Not a URL
</span>
</div>
<label>Description</label>
<textarea name="description" ng-model="editProject.project.description"></textarea>
<br>
Cancel
<button ng-click="editProject.save()" ng-disabled="myForm.$invalid"
class="btn btn-primary">
Save
</button>
<button ng-click="editProject.destroy()"
ng-show="editProject.project.$id" class="btn btn-danger">
Delete
</button>
</form>
Project tree
Can anyone point me in the right direction. Thanks
You are trying to inject projectListValue service which is not defined for your module named project.

ng-selected is not working [duplicate]

This question already has answers here:
AngularJS: ng-selected doesn't show selected value [duplicate]
(2 answers)
Closed 4 years ago.
ng-selected is not working
i select the record for the monitors
and modal opens up with the data for that specific record but combo is not selected
but when i inspect the html it ng-selected is true.
here is the code for html
<h1>Product</h1>
<div id="addProductModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="hModalh4Prod" >Add Product</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-3">Product Name</label>
<input class="form-control" type="text" name="txtproductname" id="txtproductname" maxlength="200" ng-model="vm.product.productName" />
</div>
<div class="form-group">
<label class="control-label col-md-3">Category Name</label>
<!--<input class="form-control col-md-9" type="text" name="txtcategoryname" id="txtcategoryname" maxlength="200" ng-model="vm.category.CategoryName" />-->
<select id="cmbcategory" name="cmbcategory" class="form-control" ng-model="vm.product.categoryId">
<option ng-repeat="cat in vm.Category"
ng-selected="{{cat.categoryID == vm.product.categoryId}}"
value="{{cat.categoryID}}">
{{cat.categoryName}}
{{cat.categoryID == vm.product.categoryId}}
</option>
</select>
</div>
<div class="form-group">
<label class="control-label col-md-3">Product Price</label>
<input class="form-control" type="number" name="txtptoductprice" id="txtptoductprice" maxlength="200" ng-model="vm.product.productPrice" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.reset()">Close</button>
<button type="button" id="btnSubmitProd" class="btn btn-primary" ng-disabled="!(vm.product.productName && vm.product.productPrice)" ng-click="vm.add()">Add</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-md-offset-10">
<span class="fa fa-plus fa-200px"></span> Add New Record
</div>
</div>
<table class="table table-responsive table-hover">
<thead>
<tr>
<th>Product Name</th>
<th>Category Name</th>
<th>Product Price</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="prod in vm.Products">
<td style="vertical-align:middle">{{prod.productName}}</td>
<td style="vertical-align:middle">{{prod.category.categoryName}}</td>
<td style="vertical-align:middle">{{prod.productPrice}}</td>
<td>
<input type="button" class="btn btn-sm btn-primary" ng-click="vm.edit(prod.productID)" value="Edit" />
<input type="button" class="btn btn-sm btn-primary" ng-click="vm.delete(prod.productID)" value="Delete" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
console.log("In document ready");
});
</script>
and here is the controller
(function () {
'use strict';
app.controller('productController', ['$http', '$location', 'authService', 'ngWEBAPISettings', productController]);
///productController.$inject = ['$location'];
function productController($http, $location, authService, ngWEBAPISettings) {
/* jshint validthis:true */
////debugger;
var vm = this;
vm.title = 'Product';
var d = new Date();
//Creating headers for sending the authentication token along with the system.
var authheaders = {};
authheaders.Authorization = 'Bearer ' + authService.getToken();
//For Cache needs to be updated
var config = {
headers: {
'Authorization': authheaders.Authorization
},
cache: false,
};
vm.Products = [];
vm.Category = [];
vm.product = {
categoryId: 0,
productID:0,
productName: "",
productPrice:0,
createdOn: d,
updatedOn:d
};
//For Populating the Category Combo
vm.getCategory = function () {
////debugger;
////For Grid
$http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Categories?unique=" + new Date().getTime(), config)
.then(function (respose) {
////success
////debugger;
angular.copy(respose.data, vm.Category);
////failure;
//var i = 2;
////debugger;
}, function (response) {
//failure
////debugger;
}).finally(function () {
////debugger;
//finally
}
);
}
////For Grid.
vm.getProducts = function () {
////debugger;
////For Grid
$http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Products?unique=" + new Date().getTime(), config)
.then(function (respose) {
////success
////debugger;
angular.copy(respose.data, vm.Products);
////failure;
//var i = 2;
////debugger;
}, function (response) {
//failure
////debugger;
}).finally(function () {
////debugger;
//finally
}
);
}
//// For adding the new record.
vm.add = function () {
////authheaders.Content-Type="application/x-www-form-urlencoded";
////debugger;
////alert('in add');
vm.product.createdOn = d;
vm.product.updatedOn = d;
$http.post(ngWEBAPISettings.apiServiceBaseUri + "api/Products", JSON.stringify(vm.product), { headers: authheaders })
.then(function (repose) {
////success
////debugger;
vm.Products.push(repose.data);
alert('Category has been addded successfully');
$('#addProductModal').modal('hide');
}, function (response) {
////failure
////debugger;
alert('An error has been occurred while adding the data');
}).finally(function () {
vm.category = {};
});
}
////For showing the edit modal and do events setting to call update instead of add.
vm.edit = function (id) {
///debugger;
////var id = vm.category.categoryID;
////vm.category = {};
$http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Products/" + id, config)
.then(function (response) {
//success
debugger;
//show modal
$('#btnSubmitProd').html('Update');
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.editFinal);
$('#hModalh4Prod').html('Edit Product');
$('#addProductModal').modal('show');
vm.product = response.data;
////vm.getCategory();
//vm.category.CategoryID = response.data.categoryID;
//vm.category.CategoryName = response.data.categoryName;
//vm.category.CreatedOn = response.data.createdOn;
//vm.category.UpdatedOn = response.data.updatedOn;
////categoryID = response.data.categoryID;
//vm.category = {};
}, function (response) {
//failure
debugger;
alert('Unable to fetch the data for desired id.');
}).finally(function () {
})
}
////For doing the final update of edited record and save it into the db.
vm.editFinal = function () {
////debugger;
//// alert('in update final' + categoryID);
//goes in finally
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.add);
$http.put(ngWEBAPISettings.apiServiceBaseUri + "api/Products/" + vm.category.CategoryID, JSON.stringify(vm.category), { headers: authheaders })
.then(function (response) {
//success
////debugger;
updateProduct(vm.category.CategoryID, vm.category);
alert('Record has been updated successfully');
$('#addProductModal').modal('hide');
}, function (response) {
//failure
/////debugger;
alert('There has been error while updating the record');
}).finally(function () {
//final
////debugger;
vm.category = {};
})
}
vm.delete = function (id) {
////debugger;
///alert(id);
if (confirm('Are you sure you want to save this thing into the database?')) {
$http.delete(ngWEBAPISettings.apiServiceBaseUri + "api/Products/" + id, { headers: authheaders })
.then(function (reponse) {
////debugger;
deleteProduct(id);
alert('Record has been delete successfully');
}, function (response) {
/////debugger;
alert('There is some problem in delete record');
}
).finally(function () { })
}
else {
// Do nothing!
}
}
////For resetting Product object after close of modal.
vm.reset = function () {
vm.category = {};
}
activate();
function activate() {
vm.getProducts();
vm.getCategory();
////This event is fired immediately when the hide instance method has been called.
///called to reset the events and the headers.
$('#addProductModal').on('hidden.bs.modal', function () {
////debugger;
vm.category = {};
$('#btnSubmitProd').html('Add');
$('#hModalh4Prod').html('Add Category');
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.add);
console.log("modal is closed hidden");
})
////This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).
///called to reset the events and the headers.
$('#addProductModal').on('hide.bs.modal', function () {
////debugger;
vm.category = {};
$('#btnSubmitProd').html('Add');
$('#hModalh4Prod').html('Add Category');
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.add);
console.log("modal is closed hide");
})
}
////update the product object in grid after update.
function updateCategory(value, product) {
for (var i in vm.Products) {
if (vm.Products[i].productID == value) {
//var cat = {};
//cat.categoryID = category.CategoryID;
//cat.categoryName = category.CategoryName;
//cat.createdOn = category.CreatedOn;
//cat.updatedOn = category.UpdatedOn;
vm.Category[i] = product;
break; //Stop this loop, we found it!
}
}
}
function deleteProduct(value) {
for (var i in vm.Products) {
if (vm.Products[i].productID == value) {
delete vm.Products.splice(i, 1);
break; //Stop this loop, we found it!
}
}
}
vm.openAddProductModal = function ()
{
vm.product = {};
$('#addProductModal').modal('show');
$('#btnSubmitProd').html('Add');
$('#hModalh4Prod').html('Add Product');
}
}
})();
it works after changing using ng-option by doing this
<select class="form-control col-md-9" ng-options="cat as cat.categoryName for cat in vm.Category track by cat.categoryID" ng-model="vm.product.category"></select>

Append Data to existing json array through Angular-Bootstrap dialog modal

I am facing issue while adding data through Angular Dialog modal
Here My plunker
http://plnkr.co/edit/EJpkmXqNAcuN3GJiLvAL?p=preview
<table class="table table-bordered">
<thead>
<tr>
<th>
<input type="checkbox" ng-model="isAll" ng-click="selectAllRows()"/>ALL
</th>
<th>
ID
</th>
<th>
NAME
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data" ng-class="{'success' : tableSelection[$index]}">
<td>
<input type="checkbox" ng-model="tableSelection[$index]" />
</td>
<td>{{row.id}}</td>
<td>{{row.name}}</td>
</tr>
</tbody>
</table>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">Im a modal!</h3>
</div>
<form name = "addFriendForm">
<input ng-model = "user.id"class="form-control" type = "text" placeholder="id" title=" id" />
<input ng-model = "user.name"class="form-control" type = "text" placeholder="name" title=" name" />
</form>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>***strong text***
Here Script.js
While trying get data from dialog modal it was not coming
Can you please any one help me out of this problem
var app = angular.module('myapp', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope,$modal,$log) {
$scope.user = {id: "",name:""}
$scope.data = [{
id: 1,
name: 'Name 8'
}, {
id: 2,
name: 'Name 7'
}];
$scope.tableSelection = {};
$scope.isAll = false;
$scope.selectAllRows = function() {
//check if all selected or not
if ($scope.isAll === false) {
//set all row selected
angular.forEach($scope.data, function(row, index) {
$scope.tableSelection[index] = true;
});
$scope.isAll = true;
} else {
//set all row unselected
angular.forEach($scope.data, function(row, index) {
$scope.tableSelection[index] = false;
});
$scope.isAll = false;
}
};
$scope.removeSelectedRows = function() {
//start from last index because starting from first index cause shifting
//in the array because of array.splice()
for (var i = $scope.data.length - 1; i >= 0; i--) {
if ($scope.tableSelection[i]) {
//delete row from data
$scope.data.splice(i, 1);
//delete rowSelection property
delete $scope.tableSelection[i];
}
}
};
$scope.addNewRow = function() {
//set row selected if is all checked
$scope.tableSelection[$scope.data.length] = $scope.isAll;
$scope.data.push({
id: $scope.data.length,
name: 'Name ' + $scope.data.length
});
};
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
data: function () {
return $scope.data;
}
}
});
modalInstance.result.then(function (data) {
$scope.user = data;
$scope.data.push($scope.user);
// $scope.data.push({'id':$scope.data.id,'name':$scope.data.name});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
angular.module('myapp').controller('ModalInstanceCtrl', function ($scope, $modalInstance, data) {
$scope.ok = function () {
$modalInstance.close($scope.user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
You should create $scope.user object in your ModalInstanceCtrl and add $scope.user in your $modalInstance.close like this:
angular.module('myapp').controller('ModalInstanceCtrl', function ($scope,$modalInstance) {
$scope.user = {};
$scope.ok = function () {
$modalInstance.close($scope.user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
I've checked this in your plunker, so it works

Resources