I have two pages-one is to create data and when I click save button text box values will be send to backend method.In another page am displaying those entered datas in table.So am using two controller methods here.
I dont know how to send text box values to backend using angular.I did it using jquery simply but I dont know angular thats why am struggling.
This is my first page to save text box details:
<div class="row ">
<label>Name<span id="required">*</span></label>
<input type="text" ng-model="item.name" class = "col-lg-5 col-md-5 col-sm-5 col-xs-10"/>
</div>
<div class="row ">
<label class="col-lg-2 col-md-2 col-sm-3 col-xs-12 ">Description</label>
<textarea ng-model="item.description"></textarea>
</div>
<div class="row marTop">
<span class="pull-right">
<button class="btn save btn-primary" ng-click="addItem(item)"><i class="fa fa-floppy-o"></i>Save</button>
<button class="btn cancel btn-default" onclick="window.location.href = '/Admin/RoleList'"><i class="fa fa-ban"></i>Cancel</button>
</span>
</div>
Script: In this method only I need to pass name and description values
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http) {
$scope.items = [];
$scope.addItem = function (item) {
$scope.items.push(item);
$scope.item = {};
}
//$scope.item = aaa;
console.log(item)
//$scope.values = {
// name: 'newroleName',
// description: 'roledescription'
//};
$http.post("/Admin/RolesInsert"){
alert("success")
}
})
</script>
This is my second page to get table data( that saved name should be display in this table)
<table class="table table-hover table-bordered" id="mydata" ng-controller="myCtrl">
<thead class="colorBlue">
<tr>
<th>S.No</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="">
<tr ng-repeat="x in roleList | filter:searchText">
<td>{{x.Id}}</td>
<td>{{x.name}}</td>
<td>
<i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="edit{{x.Id}}"></i>
<i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-click="update{{x.Id}}"></i>
<i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="cancel{{x.Id}}"></i>
</td>
</tr>
</tbody>
</table>
script for second table
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http) {
$scope.values = {
};
$http.post("/Admin/getRolesList")
.then(function (response) {
$scope.roleList = response.data;
});
})
</script>
One of the ways of doing this is:
angular.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http, myFactory) {
...
function sendDataToBackend() {
var requestHeaders = {
"Content-Type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: 'your url',
headers: requestHeaders
};
httpRequest.data = $scope.items;
$http(httpRequest).then(function (response) {
//Handle the response from the server
})
}
}
Finally got an answer:
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', ["$scope","$http", function ($scope, $http ,myFactory) {
$scope.items = [];
$scope.addItem = function (item) {
$scope.items.push(item);
//$scope.oRoles = $scope.item
$scope.json = angular.toJson($scope.item);
console.log($scope.json)
}
$scope.myFunc = function (item) {debugger
$scope.addItem(item);
var requestHeaders = {
"Content-Type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: '/Admin/RolesInsert',
headers: requestHeaders
};
httpRequest.data = $scope.json;
$http(httpRequest).then(function (response) {
alert(response)
//$window.location.href = '/Admin/RoleList';
})
}
}])
</script>
Related
When my scope has two properties that each contain an array retrieved asynchronously from the database, I cannot elegantly access the one from the other. I'm sure I must be missing something because my current solution feels like a hack.
I have an Angular CRUD page that contains a table and a form which contains a dropdown select control. When I click on a row in the table and want to update it, I need to populate the dropdown with the current value. In order to get this right, I'm currently declaring a global variable and assign the array used to populate the dropdown to that variable once it is retrieved from the database.
var columnHeaderArray;
var app = angular.module('myApp', []);
app.controller('ColumnHeadingController',
function ($scope, $http) {
$scope.GetAllData = function () {
$http({
method: "get",
url: "/api/Staat8Maintenance/GetAllColumnHeadings"
}).then(function (response) {
$scope.columnheaders = response.data;
$scope.GetGroupHeaderData();
},
function () { alert("Error Occured"); });
};
$scope.GetGroupHeaderData = function () {
$http({
method: "get",
url: "/api/Staat8Maintenance/GetGroupHeadingsForCombo"
}).then(function (response) {
$scope.groupheaders = response.data;
columnHeaderArray = response.data;
},
function () { alert("Error Occured"); });
};
$scope.UpdateColumnHeading = function (cho) {
document.getElementById("OriginalOrder").innerHTML = cho.ColumnOrder;
document.getElementById("OriginalColumnHeading").innerHTML = cho.ColumnHeading;
$scope.ColumnHeading = cho.ColumnHeading;
$scope.ColumnOrder = cho.ColumnOrder;
$scope.SelectedOption = columnHeaderArray[columnHeaderArray.findIndex(x => x.GroupingHeaderId == cho.GroupingHeaderId)];
document.getElementById("btnSave").setAttribute("value", "Update");
document.getElementById("btnSave").style.backgroundColor = "Yellow";
document.getElementById("formColumnHeading").style.display = "block";
};
}
);
<div id="SubAccountGrouping" class="tabcontent"
ng-controller="ColumnHeadingController"
ng-init="GetAllData()">
<h2>Column Headings</h2>
<h5>This is where the column headings will be maintained.</h5>
<div id="formColumnHeading" class="form" role="form">
<div class="container">
<div class="row">
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-1 edittextwide">Heading:</label>
<div class="col-sm-6">
<input type="text" class="form-control edittextwide"
id="inputColumnHeading"
placeholder="Column Heading"
ng-model="ColumnHeading" />
</div>
</div>
<div class="form-group">
<label class="col-sm-1">Order:</label>
<div class="col-sm-6">
<input type="number" class="form-control"
id="inputColumnOrder"
placeholder="Order"
ng-model="ColumnOrder" />
</div>
</div>
<div class="form-group">
<label class="col-sm-1 edittextwide">Group Heading:</label>
<div class="col-sm-6">
<select class="form-control edittextwide"
name="groupHeadings"
id="selectGroupHeadings"
ng-model="SelectedOption"
ng-options="gh as gh.HeadingName for gh in groupheaders track by gh.GroupingHeaderId">
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div>
<input type="button" id="btnSave" class="form-control btn-default"
value="Submit" ng-click="InsertData()" />
</div>
</div>
</div>
<div class="hiddenlabel">
<label id="OriginalOrder">0</label>
<label id="OriginalColumnHeading">ABC</label>
</div>
</div>
<div class="scrolldiv">
<table class="table">
<thead>
<tr>
<th>Heading</th>
<th>No of Sub-Accounts</th>
<th>Column Order</th>
<th>Group Heading</th>
<th>Parent Group Heading</th>
<th>Include in Staat 8</th>
<th>Actions</th>
</tr>
</thead>
<tr ng-repeat="cho in columnheaders">
<td>{{cho.ColumnHeading}}
</td>
<td>{{cho.NumberOfEntries}}
</td>
<td>{{cho.ColumnOrder}}
</td>
<td>{{cho.GroupHeading}}
</td>
<td>{{cho.ParentGroupHeading}}
</td>
<td>{{cho.IncludeInStaat8?'Yes':'No'}}
</td>
<td>
<input type="button" class="btn btn-warning"
value="Update"
ng-click="UpdateColumnHeading(cho)" />
</td>
</tr>
</table>
</div>
</div>
When I try to set $scope.SelectedOption using $scope.groupheaders directly, it bombs out. I realise this is because of the asynchronous nature, but I suspect there must be a more elegant way to achieve this?
// include $q to use promises
function ($scope, $http, $q) {
// create a deferred promise
var q = q.defer();
// call the first $http method and store the promise
var promise1 = $http(config1);
// call the second $http method and store the promise
var promise2 = $http(config2);
// handle when the first promise resolves
promise1
.then( (data) => {
$scope.columnheaders = response.data;
})
.catch( (errors) => q.reject(errors));
// handle when the second promise resolves
promise2
.then( (data) => {
$scope.groupheaders = response.data;
})
.catch( (errors) => q.reject(errors));
// wait for both promises to resolve then do final actions
$q.all([promise1, promise2])
.then( () => {
columnHeaderArray = response.data;
q.resolve();
});
// return the promise for calling methods to wait until this resolves
return q.promise;
}
Reference for using $q
Reference for using $http
You can streamline the above code to make it more condensed, but I've broken it out some to be a little easier to follow.
I am bit new to AngularJS.
Here is my code:
table.js
.controller('ModalDemoCtrl', function ($scope, $rootScope, $uibModal, $log, tableService) {
$rootScope.$on("openRootDialog", function(event, html){
$scope.openDialog(html);
});
$scope.openDialog = function (html) {
// TODO: replace option dialog with your options:
var modalInstance = $uibModal.open({
animation: true,
templateUrl: html + '.html',
controller: 'ModalInstanceCtrl',
size: 'md',
backdrop: 'static',
keyboard: true,
resolve: {
content: function () {
return $scope.modalContent;
}
}
});
modalInstance.result.then(function (result) {
// Add user in you database
tableService.addUserData(result);
// Add user in your view
$scope.data.push(result)
$scope.tableEdit.reload();
});
}
})
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, content) {
$scope.modalContent = content;
$scope.ok = function () {
$modalInstance.close($scope.user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
})
//user
.controller('tableUserCtrl', function($scope, $rootScope, $uibModal, $log, $filter, $sce, ngTableParams, tableService) {
//var data = tableService.data;
var selfUser = this;
$scope.data = [];
//selfUser.obj = null;
var promise = tableService.getUserData();
promise.then(
function(payload) {
$scope.data = payload.data;
$scope.tableEdit = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'asc' // initial sorting
}
}, {
total: $scope.data.length, // length of data
getData: function($defer, params) {
//$defer.resolve(selfUser.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
//sorting
var orderedData = params.sorting() ? $filter('orderBy')($scope.data, params.orderBy()) : $scope.data;
//filtering
orderedData = params.filter() ? $filter('filter')(orderedData, params.filter()) : orderedData;
//orderedData = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
//params.total(orderedData.length);
//$defer.resolve(orderedData);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
},
function(errorPayload) {
$log.error('failure loading movie', errorPayload);
});
//to update data
$scope.updateUser = function(w) {
tableService.updateUserData(w);
}
$scope.removeUser = function(id, w) {
tableService.removeUserData(id)
//alert(JSON.stringify($scope.data))
$scope.data.splice($scope.data.indexOf(w), 1);
$scope.tableEdit.reload();
//alert(JSON.stringify($scope.data))
}
$scope.openUserDialog = function(html) {
$rootScope.$emit("openRootDialog", {});
}
})
view.html
<div class="container" data-ng-controller="tableUserCtrl">
<!--<div class="p-t-0" data-ng-controller="ModalDemoCtrl"> -->
<script type="text/ng-template" id="adduser.html">
<div class="modal-header">
<!--<h4 class="modal-title">Add User</h4>-->
</div>
<form role="form" ng-submit="insertInfo(userInfo);" name="userForm" novalidate>
<div class="modal-body m-l-15">
<div class="row">
<div class="form-group fg-float m-b-30">
<div class="fg-line">
<input type="text" class="input-sm form-control fg-input" name="name" ng-model="user.name" required="">
<label class="fg-label">Name</label>
</div>
<div ng-show="userForm.$submitted || userForm.name.$touched">
<div ng-show="userForm.name.$error.required" class="error">This field is required.</div>
</div>
</div>
...
</div>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="ok(user);" ng-disabled="userForm.$invalid">Submit</button>
<button class="btn btn-link" ng-click="cancel()">Cancel</button>
</div>
</form>
</script>
<button class="btn btn-default pull-right" ng-click="openUserDialog('adduser')">Add User</button><br/><br/>
<!--</div>-->
<div class="card">
<div class="card-header">
<h2>Users <small></small></h2>
</div>
<div class="card-body">
<div class="table-responsive">
<table ng-table="tableEdit" class="table table-striped table-vmiddle" show-filter="true">
<tr ng-repeat="w in $data" ng-class="{ 'active': w.$edit }">
<td data-title="'Name'" filter="{ 'name': 'text' }" sortable="'name'">
<span ng-if="!w.$edit">{{ w.name }}</span>
<div ng-if="w.$edit"><input class="form-control" type="text" ng-model="w.name" /></div>
</td>
...
<td data-title="'Actions'">
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="w.$edit = true"><i class="zmdi zmdi-edit"></i></button>
<button type="button" class="btn btn-default" ng-if="!w.$edit" ng-click="removeUser(w.user_id, w)"><i class="zmdi zmdi-close"></i></button>
<button type="button" class="btn btn-success" ng-if="w.$edit" ng-click="w.$edit = false; updateUser(w)"><i class="zmdi zmdi-check"></i></button>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
I am passing html template name in openUserDialog function from view as I need to use that name in openDialog function written in ModalDemoCtrl so I can use dynamic templates in modal.
I have searched a lot but couldn't get exact things that how can I pass args to openRootDialog from openUserDialogfunction written in tableUserCtrl?
can anyone please help me? is there any syntax issue? I don't have any idea about $emit, $on etc. as am using it first time.
Use $rootscope,
this is example:
app.run(function($rootScope) {
$rootScope.someMethod=function(){
//do staff
}
}
in another controller just use $scope.someMethod(), in view someMethod().
it is global method now.
I used to have all my code in one big js file, but i separated everything -- including controllers to make it modular as my little app grows (and for learning porpoises). So my ui-bootstrap modal code is in this controller and is called and worked fine. When i split the controllers into separate files i get the error below. How do i fix?
app.js
var personApp = angular.module('PersonApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
personController.js
personApp.controller('PersonController', function ($scope, $uibModal, PersonService) {
$scope.addPerson = function () {
$scope.modalModel = {
Id: 0,
firstName: '',
lastName: '',
birthDate: ''
};
$scope.$uibModalInstance = $uibModal.open({
templateUrl: '/Modal/AddEditPersonModal',
controller: 'ModalController',
scope: $scope
})
}
personModalController.js
personApp.controller('ModalController', ['$scope', function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<link href="~/Content/PageSpecific/Index.css" rel="stylesheet" />
<script src="~/Scripts/PersonApp/app.js"></script>
<script src="~/Scripts/PersonApp/filters/personFilter.js"></script>
<script src="~/Scripts/PersonApp/services/personService.js"></script>
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
<script src="~/Scripts/PageSpecific/Index.js"></script>
<div ng-app="PersonApp" class="container">
<div ng-controller="PersonController">
<div class="mb20 mt15">
<input type="text" placeholder="Search Person" ng-model="searchPerson" />
<button type="button" class="btn btn-primary pull-right mb15 mr20" data-toggle="modal" ng-model="addPersonModel" ng-click="addPerson()">Add New</button>
</div>
<table class="table header-fixed">
<thead>
<tr>
<th ng-click="sortData('Id')">
ID <div ng-class="getSortClass('Id')"></div>
</th>
<th ng-click="sortData('firstName')">
First Name <div ng-class="getSortClass('firstName')"></div>
</th>
<th ng-click="sortData('lastName')">
Last Name <div ng-class="getSortClass('lastName')"></div>
</th>
<th ng-click="sortData('birthDate')">
BirthDate <div ng-class="getSortClass('birthDate')"></div>
</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in filteredPersons | orderBy: sortColumn:reverseSort | filter : searchPerson">
<td>{{person.Id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
<td>{{person.birthDate | date:"MM/dd/yyyy"}}</td>
<td>
<span class="fa fa-pencil-square-o"></span>
<span class="fa fa-remove"></span>
</td>
</tr>
</tbody>
</table>
<ul uib-pagination total-items="persons.length" ng-model="currentPage" max-size="maxSize" class="pagination-sm" boundary-links="true" rotate="false" items-per-page="numPerPage" num-pages="numPages"></ul>
<pre>Page: {{currentPage}} / {{numPages}}</pre>
</div>
</div>
<style>
</style>
Was a simple mistake on my part. Changed the order of referenced files in the index.cshtml. personController had function trying to call modalcontroller (in personmodalcontroller)
This:
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
Became this:
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
You missed to include,$uibModalInstance
personApp.controller('ModalController', ['$scope' function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);
Re define the ModalController like this. You have not injected the $uibModalInstance dependency in your controller. the $uibModalInstance inside the function parameters are only the alias reference to your dependency. You have to inject the dependency first before aliasing the dependency.
personApp.controller('ModalController', ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);
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.
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>