I want to create a application which show the data of people and once the single person is clicked it has to show the details of the person.
I have created id for json file using (index of json) but I don't know how to pass the seperate id to the popup function.
<div class="content-wrapper" ng-controller="ListController">
<section class="content">
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<div ng-controller="MainCtrl" class="container">
<!--controller="MainCtrl"-->
<table class="table table-hover" ng-model="artists">
<tr>
<th>Name</th>
<th>Profile</th>
<th>First Name</th>
<th>Date</th>
<th>Status</th>
<th>Reknown</th>
</tr>
<tr ng-repeat="item in artists | filter: query | orderBy: artistOrder:direction" id="table-cursor">
<modal title="{{artists.indexOf(item)}}" visible="showModal">
<form role="form">
<div class="form-group">
<label for="text">Name</label>
<input type="text" class="form-control" id="email" placeholder="Name" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" />
</div>
<button type="submit" class="btn btn-default">Send</button>
</form>
</modal>
<td ng-click="toggleModal(artists.indexOf(item))"><span value="{{artists.indexOf(item)}}"></span>{{item.name}}</a>
</td>
<td ng-click="toggleModal()"><span value="{{artists.indexOf(item)}}">
</span>
<img ng-src="images/{{item.shortname}}_tn.jpg" width="35" height="35" alt="profile">
</td>
<td ng-click="toggleModal()"><span value="{{artists.indexOf(item)}}"></span>
<h5>{{item.shortname}}</h5>
</td>
<td ng-click="toggleModal()"><span value="{{artists.indexOf(item)}}"></span>11-7-2014</td>
<td ng-click="toggleModal()"><span value="{{artists.indexOf(item)}}"></span><span class="label label-success">Approved</span>
</td>
<td ng-click="toggleModal()"><span value="{{artists.indexOf(item)}}"></span>{{item.reknown}}</td>
<tr>
</table>
</div>
<!--controller="MainCtrl"-->
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
var myApp = angular.module('myApp', [
'ngRoute',
'myApp'
]);
myApp.controller('ListController', ['$scope', '$http', '$routeParams',
function($scope, $http, $routeParams) {
$http.get('angular/data.json').success(function(data) {
$scope.artists = data;
$scope.artistOrder = 'name';
$scope.whichItem = $routeParams.itemId;
});
}
]);
myApp.controller('MainCtrl', ['$scope', '$http', '$routeParams',
function($scope, $http, $routeParams) {
$http.get('angular/data.json').success(function(data) {
$scope.showModal = false;
$scope.artists = data;
$scope.whichItem1 = $routeParams.itemId;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
});
}
]);
myApp.directive('modal', function() {
return {
template: '<div class="modal">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ title }}</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace: true,
scope: true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value) {
if (value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = false;
});
});
}
};
});
you need to recieve your index in the method toggleModal:
$scope.toggleModal = function($index) {
// here you need to get the user info and
//set the result to $scope variable that you can you into the modal
$scope.userInfo = $scope.artists[$index];
};
Then you could use the userInfo by editing your HTML like that:
<div class="form-group">
<label for="text">Name</label>
<input type="text" class="form-control" id="email" placeholder="Name" value="{{userInfo.name}}"/>
</div>
Edit:
HTML tag "modal " with attribute "visible= true" gives angular [$rootScope:inprog] error and actually I'm reaching for the reason for this. So I highly recommend you to use the standard bootstrap modal window. Just replace your "modal" html
<modal title="{{artists.indexOf(item)}}" visible="showModal">
<form role="form">
...
</form>
</modal>
with the following:
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Chat box</h4>
</div>
<div class="modal-body">
<form role="form">
<div class="form-group">
<label for="text">"name"</label>
<input type="text" class="form-control" id="email" placeholder="Name" ng-value="userInfo.name"/>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" value="{{userInfo.password}}"/>
</div>
<button type="submit" class="btn btn-default">Send</button>
</form> </div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Then you can show it from your controller just like this:
$scope.toggleModal = function($index){
$("#myModal").modal({show: true});
$scope.userInfo=$scope.artists[$index];
};
I hope this helps :)
Edit:
If you want to open dialog modal without affecting the background, just you need to get rid of the "backdrop". So, After modal initiation
$("#myModal").modal({show: true});
just add the code below
$('.modal-backdrop').removeClass("modal-backdrop");
$('#myModal').css('display', 'table')
Related
Hi everyone I am starting with angularJS and I trying to add a route to an application but I am receiving nothing, I am using a directive too, I dont know if that is the problem.
So I have 5 different files and I am trying to route tripsView.html into Trips.cshtml with ng-view
I really appreciate your time and help
This is my code:
app-trip.js
"use strict";
var app = angular.module("app-trips",["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/",
{
controller: "tripsController",
//controllerAs: "trip",
templateUrl: "/views/tripsView.html"
});
$routeProvider.otherwise({ redirectTo: "/" });
});
simpleControl.js
app.directive("waitCursor", function waitCursor() {
return {
scope: {
show: "=displayWhen"
},
restrict: "E",
templateUrl: "/views/waitCursor.html"
};
});
tripsController.js
(function () {
"use strict";
app.controller("tripsController", function ($scope, $http) {
$scope.trips = [];
$scope.errorMessage = "";
$scope.isBusy = true;
$http.get("/api/trips")
.then(function(response) {
//Success
angular.copy(response.data, $scope.trips);
},
function(error) {
//Failure
$scope.errorMessage = "Failed to load data: " + error;
})
.finally(function() {
$scope.isBusy = false;
});
$scope.addTrip = function (newTrip) {
newTrip.dateCreated = new Date();
$scope.isBusy = true;
$scope.errorMessage = "";
$http.post("/api/trips", newTrip)
.then(function (response) {
$scope.trips.push(response.data);
$scope.newTrip = {};
// Success
},
function() {
// Failure
$scope.errorMessage = "Failed to save new trip";
})
.finally(function() {
$scope.isBusy = false;
});
};
});
})();
Trips.cshtml
#model IEnumerable<TheWorld.Models.Trip>
#{
ViewBag.Title = "Home Page";
}
<script src="~/lib/angular/angular.min.js"></script>
<script src="~/lib/angular-route/angular-route.min.js"></script>
<script src="~/js/app-trips.js"></script>
<script src="~/js/tripsController.js"></script>
<script src="~/js/simpleControls.js"></script>
<div ng-app="app-trips" class="row" >
<div ng-view></div>
<div class="col-md-6 #*col-xs-8*#">
<h1>The World</h1>
<p>This will be a fun website soon</p>
<form>
<div class="form-group">
<label>Date </label>
<input class="form-control" />
</div>
<div class="form-group">
<label>Location</label>
<input class="form-control" />
</div>
<div>
<input type="submit" value="Add" class="btn btn-success" />
</div>
</form>
</div>
</div>
<div class="col-md-6 #*col-xs-4*#">
<h2>The Map</h2>
#foreach (var item in Model)
{
<li> #item.Name: #item.DateCreated.ToString("d") </li>
}
</div>
tripsView.html --------------------------------------
<div class="col-md-6 col-md-offset-3">
<div class="text-danger" ng-show="errorMessage"> {{ errorMessage}}</div>
<wait-cursor display-when="isBusy"></wait-cursor>
<table class="table table-responsive table-striped">
<tr ng-repeat="trip in trips">
<td>{{ trip.name }}</td>
<td>{{ trip.dateCreated | date:'MM-dd-yyyy' }}</td>
<td>
<a
href="" class="btn btn-sm btn-primary">Manage
</a>
</td>
</tr>
</table>
<form novalidate name="newTripForm" ng-submit="addTrip(newTrip)">
<div class="form-group">
<label for="name">Trip Name</label>
<input class="form-control" type="text" id="name" value="name" ng-model="newTrip.name" required ng-minlength="5" />
</div>
<div class="form-group">
<input type="submit" value="Add" class="btn btn-success btn-sm" ng-disabled="newTripForm.$invalid" />
<span ng-show="newTripForm.$error.required" class="text-warning"> Name is required</span>
<span ng-show="newTripForm.$error.minlength" class="text-warning"> Name must be at least 5 characters</span>
</div>
</form>
</div>
I’m trying to post Form and including angular-ui as one of element in form (http://plnkr.co/edit/6S881qNp3v7UI4Bo9pko?p=preview), whenever I am clicking “Insert Below”, form is getting posted (in addition to inserting one more input field)
event.stopPropagation() will also not work as to add tree ui , I have to take scope on parent and as soon as I get that, ng-click of parent is also getting called
Parent Controller
var app = angular.module('crudApp', [ 'ui.router', 'ngStorage', 'clockApp',
'myApp', 'plunker', 'radioB', 'timeTicker', 'TodoApp' ]);
app.constant('urls', {
BASE : 'localhost:3030',
USER_SERVICE_API : 'localhost:3030'
});
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider.state('home', {
url : '/',
templateUrl : 'partials/list',
controller : 'UserController',
controllerAs : 'ctrl',
resolve : {
users : function($q, UserService) {
console.log('Load all users');
var deferred = $q.defer();
UserService.loadAllUsers().then(deferred.resolve,
deferred.resolve);
return deferred.promise;
}
}
});
$urlRouterProvider.otherwise('/');
} ]);
Child Controller
var app = angular.module('plunker', ['ui.tree']);
app.directive('focus', function($timeout) {
return {
restrict: 'AC',
link: function(scope, element) {
$timeout(function(){
element[0].focus();
}, 0);
}
};
});
app.controller('MainCtrl', function($scope) {
$scope.nodes = [{
value: "",
price: "",
nodes: []
}]
});
View - list.ftl
Everything is working fine except the data is saving from child controller’s
ng-click instead of parent (form input)
<div class="generic-container">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="lead">User </span>
</div>
<div class="panel-body">
<div class="formcontainer">
<div class="alert alert-success" role="alert"
ng-if="ctrl.successMessage">{{ctrl.successMessage}}</div>
<div class="alert alert-danger" role="alert"
ng-if="ctrl.errorMessage">{{ctrl.errorMessage}}</div>
<form ng-submit="ctrl.submit()" name="myForm" class="form-
horizontal">
<input type="hidden" ng-model="ctrl.user.id" />
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable"
for="uname">Name</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.name"
id="uname"
class="username form-control input-sm"
placeholder="Enter your name" required ng-minlength="3" />
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="pnumber">Phone
Number</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.pnumber" id="pnumber"
class="username form-control input-sm"
placeholder="Phone Number" required ng-minlength="3"
ng-maxlength="10" ng-pattern="ctrl.onlyNumbers" />
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="address">Address</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.address" id="address"
class="username form-control input-sm" placeholder="Address"
required ng-minlength="3" />
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="work">Work</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.work" id="work"
class="username form-control input-sm" placeholder="Work"
required ng-minlength="3" />
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="price">Price</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.price" id="price"
class="form-control input-sm" placeholder="Price" required
ng-pattern="ctrl.onlyNumbers" />
</div>
</div>
</div>
<!-- Adding multinode value - start -->
<div ng-controller="MainCtrl">
<script type="text/ng-template" id="nodes_renderer.html">
<div ui-tree-handle>
<div class='form-group'>
<input class='username form-control input-sm' ng-model='node.value' focus>
<input class='form-control' ng-model='node.price' focus>
</div>
<button class='btn btn-primary btn-sm' ng-click='$parentNodesScope.$modelValue.splice($index+1,0,{value:"New", nodes:[]});'>Insert below</button>
<button class='btn btn-primary btn-sm' ng-click='node.nodes.push({value: "New", nodes:[]});'>Insert child</button>
</div>
</script>
<div ui-tree>
<ol ui-tree-nodes ng-model="nodes" id="tree-root">
<li ng-repeat="node in nodes" ui-tree-node ng-include="'nodes_renderer.html'"></li>
</ol>
</div>
{{nodes}}
</div>
<div class="row">
<div class="form-actions floatRight">
<input type="submit" value="{{!ctrl.user.id ? 'Add' : 'Update'}}"
class="btn btn-primary btn-sm"
ng-disabled="myForm.$invalid || myForm.$pristine">
<button type="button" ng-click="ctrl.reset()"
class="btn btn-warning btn-sm" ng-disabled="myForm.$pristine">Reset
Form</button>
</div>
</div>
</form>
</div>
</div>
</div>
I have a list of users in a page and a form in which I edit the details of those users.
the form is hidden, I want to display the form when I click on edit button and also perform the task to edit it
html:
<body ng-app="myApp" class="ng-cloak">
<div class="generic-container" ng-controller="ListController as ctrl">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="lead">List of Users </span>
</div>
<div class="tablecontainer">
<table class="table table-hover">
<thead>
<tr>
<th>ID.</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
<th>Phone No.</th>
<th width="20%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="u in ctrl.users">
<td><span ng-bind="u.id"></span></td>
<td><span ng-bind="u.username"></span></td>
<td><span ng-bind="u.address"></span></td>
<td><span ng-bind="u.email"></span></td>
<td><span ng-bind="u.phone"></span></td>
<td>
<button type="button" ng-click="ctrl.edit(u.id)"
class="btn btn-success custom-width">Edit</button>
<button type="button" ng-click="ctrl.remove(u.id)"
class="btn btn-danger custom-width">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="panel panel-default" ng-show="ctrl.users.length>0">
<div class="modal-header">
<span class="lead">User Registration Form </span>
</div>
<div class="formcontainer">
<div class="modal-body">
<form ng-submit="ctrl.submit()" name="myForm"
class="form-horizontal">
<input type="hidden" ng-model="ctrl.user.id" />
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="uname">Name</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.username" id="uname"
class="username form-control input-sm"
placeholder="Enter your name" required ng-minlength="3" />
<div class="has-error" ng-show="myForm.$dirty">
<span ng-show="myForm.uname.$error.required">This is a
required field</span> <span ng-show="myForm.uname.$error.minlength">Minimum
length required is 3</span> <span ng-show="myForm.uname.$invalid">This
field is invalid </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="address">Address</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.address" id="address"
class="form-control input-sm"
placeholder="Enter your Address. [This field is validation free]" />
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="email">Email</label>
<div class="col-md-7">
<input type="email" ng-model="ctrl.user.email" id="email"
class="email form-control input-sm"
placeholder="Enter your Email" required />
<div class="has-error" ng-show="myForm.$dirty">
<span ng-show="myForm.email.$error.required">This is a
required field</span> <span ng-show="myForm.email.$invalid">This
field is invalid </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="col-md-2 control-lable" for="phone">Phone
No.:</label>
<div class="col-md-7">
<input type="text" ng-model="ctrl.user.phone" id="phone"
class="phone form-control input-sm" ng-minlength="7"
ng-maxlength="10" placeholder="Enter your Phone Number"
required />
<div class="has-error" ng-show="myForm.$dirty">
<span ng-show="myForm.phone.$error.required">This is a
required field</span> <span ng-show="myForm.uname.$error.minlength">Minimum
length required is 7</span> <span ng-show="myForm.phone.$invalid">This
phone number is invalid </span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-actions floatRight">
<input type="submit"
value="{{!ctrl.user.id ? 'Add' : 'Update'}}"
class="btn btn-primary btn-sm" ng-disabled="myForm.$invalid">
<button type="button" ng-click="ctrl.reset()"
class="btn btn-warning btn-sm" ng-disabled="myForm.$pristine">Reset
Form</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="<c:url value='/static/js/app.js' />"></script>
<script src="<c:url value='/static/js/service/user_service.js' />"></script>
<script src="<c:url value='/static/js/controller/list_Controller.js' />"></script>
User Controller.js:
'use strict';
angular.module('myApp').controller('UserController', ['$scope', 'UserService', function($scope, UserService) {
var self = this;
self.user={id:null,username:'',address:'',email:'',phone:''};
self.users=[];
self.submit = submit;
self.edit = edit;
self.remove = remove;
self.reset = reset;
fetchAllUsers();
function fetchAllUsers(){
UserService.fetchAllUsers()
.then(
function(d) {
self.users = d;
},
function(errResponse){
console.error('Error while fetching Users');
}
);
}
function createUser(user){
UserService.createUser(user)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while creating User');
}
);
}
function updateUser(user, id){
UserService.updateUser(user, id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while updating User');
}
);
}
function deleteUser(id){
UserService.deleteUser(id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while deleting User');
}
);
}
function submit() {
if(self.user.id===null){
console.log('Saving New User', self.user);
createUser(self.user);
}else{
updateUser(self.user, self.user.id);
console.log('User updated with id ', self.user.id);
}
reset();
}
function edit(id){
console.log('id to be edited', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id === id) {
self.user = angular.copy(self.users[i]);
break;
}
}
}
function remove(id){
console.log('id to be deleted', id);
if(self.user.id === id) {//clean form if the user to be deleted is shown there.
reset();
}
deleteUser(id);
}
function reset(){
self.user={id:null,username:'',address:'',email:'',phone:''};
$scope.myForm.$setPristine(); //reset Form
}
}]);
UserService.js
'use strict';
angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){
var REST_SERVICE_URI = 'http://localhost:8080/Spring4MVCAngularJSExample/user/';
var factory = {
fetchAllUsers: fetchAllUsers,
createUser: createUser,
updateUser:updateUser,
deleteUser:deleteUser
};
return factory;
function fetchAllUsers() {
var deferred = $q.defer();
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function createUser(user) {
var deferred = $q.defer();
$http.post(REST_SERVICE_URI, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while creating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function updateUser(user, id) {
var deferred = $q.defer();
$http.put(REST_SERVICE_URI+id, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while updating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
function deleteUser(id) {
var deferred = $q.defer();
$http.delete(REST_SERVICE_URI+id)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while deleting User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
}]);
After when I click on the update button the div should hide too.
This can be done using ng-show directive. I see you are using it with the following code:
<div ng-show="ctrl.users.length>0">...</div>
This would not be trigger angular.js' data-binding. Instead it will always be equal to the initial value: ng-show="false".
Solution
Create a variable in the controller and expose it to your view:
self.showForm = false;
//when you click on the edit button
self.showForm = true;
And in your html file ng-show="ctrl.showForm"
I'm learning Angular on my own and trying to edit book from selected table row. I select it properly, I have it as variable in scope, but something goes wrong when I try to pass it via resolve in $modal.open function.
My html, where I select a row looks like that:
<!DOCTYPE html>
<html>
<body>
<div class="container">
<div class="jumbotron">
<section>
<h2>Library</h2>
<table class="table table-striped table-bordered">
<tr>
<th>
Title
</th>
<th>
Author
</th>
<th>
Genre
</th>
<th>
Year
</th>
</tr>
<tr ng-click="setSelected(book)" ng-repeat="book in books | orderBy : 'year'">
<td>
<strong>{{book.title}}</strong>
</td>
<td>
{{book.author}}
</td>
<td>
{{book.genre}}
</td>
<td>
{{book.year}}
</td>
</tr>
</table>
<div>
<button ng-click="openModal()" type="button" class="btn btn- primary">Add book</button>
<button ng-click="openEditModal()" type="button" class="btn btn- primary">Edit book</button>
</div>
</section>
</div>
</div>
</body>
</html>
Controllers of this html and modal are MyfirstController and EditModalController and are here:
angular.module('app.component1').controller('MyFirstController', function($scope, $http, $modal, response){//tu w argumentach jeszcze byly books
'use strict';
$scope.selectedBook = null;
$scope.setSelected = function (selectedBook) {
$scope.selectedBook = selectedBook;
};
$scope.books = response.data;
$scope.openModal = function () {
var modal = $modal.open({
templateUrl: '/component-1/modal-dialog/modal-dialog.tpl.html',
controller: 'MyModalController'
/*resolve: {
newBook: function() {
return;
}
}*/
});
modal.result.then(function(addedBook) {
$scope.books.push(addedBook);
});
};
$scope.openEditModal = function () {
var modal = $modal.open({
templateUrl: '/component-1/edit-dialog/edit-dialog.tpl.html',
controller: 'EditModalController',
resolve: {
selectedBook: function() {
return $scope.selectedBook;
}
}
});/*
modal.result.then(function(addedBook) {
$http.post('/component-1/books.json', addedBook);
});*/
};
}).controller('MyModalController', ['$scope', '$modalInstance', function($scope, $modalInstance, $http){ //tu w argumentach bylo jeszcze selectedBook
'use strict';
$scope.date = new Date();
//$scope.year = $scope.date.getMonth();
$scope.addedBook = {
"genre": '',
"year": $scope.date,
"title": '',
"author": ''
};
$scope.ok = function() {
$modalInstance.close($scope.addedBook);
};
}]).controller('EditModalController', ['$scope', '$modalInstance', 'selectedBook', function($scope, $modalInstance, $http, selectedBook){
'use strict';
$scope.selectedBookTitle = selectedBook.title;
$scope.selectedBookAuthor = selectedBook.author;
$scope.selectedBookGenre = selectedBook.genre;
$scope.selectedBookYear = selectedBook.year;
}]);
it is not important here, but he is my modal where I wanted the book data to be imported into inputs
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Add new book</h3>
</div>
<div class="modal-body">
<form name="modalForm">
<div class="form-group">
<label for="title">Title:</label>
<input ng-model="selectedBookTitle" ng-required="true" type="text" class="form-control" id="editTitle">
</div>
<div class="form-group">
<label for="author">Author:</label>
<input ng-model="selectedBookAuthor" ng-required="true" type="text" class="form-control" id="editAuthor">
</div>
<div class="form-group">
<label for="genre">Genre:</label>
<input ng-model="selectedBookGenre" type="text" class="form-control" id="editGenre">
</div>
<div class="form-group">
<label for="year">Release date:</label>
<datepicker min="minDate" placeholder="Set release date" show-weeks="false" id="editYear"></datepicker>
<!--<label for="year">Year:</label>-->
<!--<input ng-model="addedBook.year" ng-pattern="/^\d+$/" type="text" class="form-control" id="year">-->
</div>
</div>
<div class="modal-footer ">
<button ng-disabled="modalForm.$invalid" class="btn btn-primary">Edit book</button>
</div>
</form>
</div>
</body>
</html>
Don't look at datepickers. I need to think long about them, and how to make them working as I'd like them to.
So let's come back to the openEditModal() and resolve. I'm getting error that angular can't read property title in selectedBook.title in EditModalController or it is undefined. I'm sure I have an error in resolve in openEditModal, but I can't figure out where.
I am new in angularjs. I want to add data in database and to show in a table.There is one input name field and one image field.
my html is
service.html:
<div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="addservices" class="modal fade">
<form role="form" name="myForm" ng-submit="submitCuisine(myForm.$valid)" novalidate>
<div class="modal-dialog" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add Service</h4>
</div>
<div class="modal-body" ng-class="{ 'has-error' : myForm.cat.$invalid && myForm.cat.$touched }">
Category <input type="text" name= "cat" id= "cat" ng-model="dataform.cat" autocomplete="off" class="form-control placeholder-no-fix">
</div><br>
<div class="modal-body" ng-class="{ 'has-error' : myForm.name.$invalid && myForm.name.$touched }"> Service Name<input type="text" name= "name" id= "name" ng-model="dataform.name" autocomplete="off" class="form-control placeholder-no-fix"></div>
<div class="modal-body" ng-class="{ 'has-error' : myForm.desc.$invalid && myForm.desc.$touched }"> Description<input type="text" name= "desc" id= "desc" ng-model="dataform.desc" autocomplete="off" class="form-control placeholder-no-fix"></div>
<div class="modal-body" ng-class="{ 'has-error' : myForm.cost.$invalid && myForm.cost.$touched }"> Cost($)<input type="text" name= "cost" id= "cost" ng-model="dataform.cost" autocomplete="off" class="form-control placeholder-no-fix"></div>
<div class="modal-body" ng-class="{ 'has-error' : myForm.servicetime.$invalid && myForm.servicetime.$touched }"> Time(min)<input type="text" name= "servicetime" id= "servicetime" ng-model="dataform.servicetime" autocomplete="off" class="form-control placeholder-no-fix"></div>
<div class="modal-body"> Image <input type="file" file-input="files" name="file"/>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
<button class="btn btn-success" type="submit" ng-disabled="myForm.$invalid">Submit</button>
</div>
</div>
</div>
</form>
</div>
addserviceController.js
app.controller('addserviceController', function ($scope,$http,$cookieStore) {
$scope.submitCuisine=function(isvalid){
if(isvalid){
var fd=new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
fd.append('formdata',JSON.stringify($scope.dataform));
$http.post('admin/managecuisineAdd',fd,{
access_token : $cookieStore.get('obj').accesstoken,
transformRequest:angular.identity,
headers:{'Content-type':undefined}
}).success(function(data){
$scope.status=data;
$scope.itemlist.push(data)
$scope.message="New Dish Added Successfully"
});
}
}
});
app.js
(function(window){
var app= angular.module('customersApp',['ngRoute','ngCookies','ui.bootstrap']);
app.directive("fileInput",['$parse',function($parse){
return{
restrict:'A',
link:function(scope,ele,attrs){
ele.bind('change',function(){
$parse(attrs.fileInput).
assign(scope,ele[0].files)
scope.$apply()
});
}
}
}]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/login', {
title: 'Login',
controller: 'loginController',
templateUrl: 'app/views/loginuser.html'
})
.when('/logout', {
title: 'Logout',
templateUrl: 'partials/login.html',
controller: 'loginController'
})
.when('/dashboard', {
title: 'Dashboard',
templateUrl: 'app/views/dynamic_table.html',
controller: 'dashboard'
})
.when('/verified_artists', {
title: 'Verified Artists',
templateUrl: 'app/views/verified_artists.html',
controller: 'artistController'
})
.when('/new_artists', {
title: 'New Request Artists',
templateUrl: 'app/views/new_artists.html',
controller: 'verifyartistController'
})
.when('/services', {
title: 'Services',
templateUrl: 'app/views/services.html',
controller: 'serviceController'
})
.when('/addservices', {
title: 'Services',
templateUrl: 'app/views/services.html',
controller: 'addserviceController'
})
}]);
window.app = app;
}(window));
I have made one controller addserviceController.js. I want that when I click on Submit button, it will go to controller where I will hit an api but I don't know how to send data of name and image field and also help me what I will write in controller.Please tell me how to get data of input field and pass to the controller where it will hit an api so that data will save to database.
You should use the $http service to make AJAX requests or interact with a RESTful Service.
More detail how to use $http service is here.
Here is the code what i did in my project to upload image and data:-
HTML PAGE :-
<form role="form" name="myForm" ng-submit="submitCuisine(myForm.$valid)" novalidate>
<div class="form-group" ng-class="{ 'has-error' : myForm.name.$invalid && myForm.name.$touched }">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name"
placeholder="Name of cuisine" ng-model="dataform.name" required>
</div>
<div class="form-group" ng-class="{ 'has-error' : myForm.description.$invalid && myForm.description.$touched }">
<label for="description">Description</label>
<input type="text" class="form-control" id="description" name="description"
placeholder="Description for cuisine" ng-model="dataform.description" required>
</div>
<div class="form-group" ng-class="{ 'has-error' : myForm.category.$invalid && myForm.category.$touched }">
<label for="description">Category</label>
<select class="form-control" ng-model="dataform.category" id="category" name="category" required>
<option>Veg</option>
<option>Non-veg</option>
</select>
</div>
<div class="form-group" ng-class="{ 'has-error' : myForm.subcategory.$invalid && myForm.subcategory.$touched }">
<label for="description">Sub-Category</label>
<select class="form-control" ng-model="dataform.subcategory" id="subcategory" name="subcategory" required>
<option>Main Course</option>
<option>Staters</option>
</select>
</div>
<div class="form-group" ng-class="{ 'has-error' : myForm.price.$invalid && myForm.price.$touched }">
<label for="description">Price</label>
<span class="fa fa-dollar"></span>
<input type="number" class="form-control" id="price" name="price"
placeholder="Price" ng-model="dataform.price" required>
</div>
<div class="form-group">
<label for="description">Image</label>
<input type="file" file-input="files" name="file"/>
</div>
<button class="btn btn-primary" type="submit" ng-disabled="myForm.$invalid"> Submit</button>
</form>
Controller:-
$scope.submitCuisine=function(isvalid){
if(isvalid){
var fd=new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
fd.append('formdata',JSON.stringify($scope.dataform));
$http.post('admin/managecuisineAdd',fd,{
transformRequest:angular.identity,
headers:{'Content-type':undefined}
}).success(function(data){
$scope.status=data;
$scope.itemlist.push(data)
$scope.message="New Dish Added Successfully"
});
}
}
Directive :-
myApp.directive("fileInput",['$parse',function($parse){
return{
restrict:'A',
link:function(scope,ele,attrs){
ele.bind('change',function(){
$parse(attrs.fileInput).
assign(scope,ele[0].files)
scope.$apply()
});
}
}
}]);
Ok, I thought you could use angular-ui and the modal from bootstrap there.
This example is the one from http://angular-ui.github.io/bootstrap/ modificated for your needs.
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
< div class = "modal-header" > < h3 class = "modal-title" > I 'm a modal!</h3>
</div>
<div class="modal-body">
<label>Your Variable
<input ng-model="variable" />
</label>
<p>Variable: <b>{{ variable }}</b></p>
</div>
<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>
<button class="btn btn-default" ng-click="open()">Open me!</button>
<button class="btn btn-default" ng-click="open('lg')">Large modal</button>
<button class="btn btn-default" ng-click="open('sm')">Small modal</button>
<div ng-show="variable">Variable input from a modal: {{ variable }}</div>
</div>
</body>
</html>
and your javascript:
angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function($scope, $modal, $log) {
$scope.variable = "initial value";
$scope.open = function(size) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
variable: function() {
return $scope.variable;
}
}
});
modalInstance.result.then(function(variable) {
//your special processing here
$scope.variable = variable.toUpperCase();
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function($scope, $modalInstance, variable) {
$scope.variable = variable;
$scope.ok = function() {
$modalInstance.close($scope.variable);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
});
I'm doing the same here and everything is working fine.
working demo:
http://plnkr.co/edit/yXEGPXejWdlLrniDGQs5?p=preview