how to add data using angularjs - javascript

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

Related

How use angular routing in angujarJS 1.6.4 in VS2015

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>

Parent ng-click action is getting triggered on child ng-click (from child, need to access $parentNodesScope for angular-tree-ui)

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>

Apply autofocus on input inside ng-repeat

I want to autofocus the first input inside ngRepeat when my page loads and when I add a new item to array the focus should go for the last item of the ngRepeat and so on, doesn't matter how many items I add.
Here's my code actually:
<div class="add-top" ng-show="showstep=='step2'" style="position:relative;width:100%;">
<form name="EmailForm" novalidate accessible-form autocomplete="off" ng-submit="checkDup() && EmailForm.$valid ? Add() :''">
<div class="white text-center ">
<!-- && (emailDel | filter:'':true).length == emailDel.length -->
<div class=" bg-color-upload03 ticket-top">
<div class="col-md-12 " ng-init="emailDel=[1]">
<div class="newevent-nav01">
Enter email ids</div>
<div class="col-md-6 col-md-offset-3" ng-repeat="e in emailDel track by $index">
<input type="email" class="text-left" placeholder="Email ID" validate-email ng-model="emailDel[$index]" ng-init="emailDel[$index]=''" ng-required="emailDel.length==1" name="email_{{$index}}" id="email_{{$index}}">
<div class="col-md-2 col-md-offset-10 text-left" style="margin-top: -10px;" ng-show="(emailDel.length-1)==$index">
<img src="../../../path to + symbol-active icon" width="40%" ng-hide="(EmailForm.$valid && emailDel[ds.emailDel.length-1] !='')" />
<img src="../../..path to +symbol gray icon" width="40%" class="cursor-poi" ng-click="(EmailForm.$valid && emailDel[emailDel.length-1] !='') ? emailDel.push(emailDel.length+1) :''" ng-show="(EmailForm.$valid && emailDel[emailDel.length-1] !='')" />
</div>
<div class="col-md-12">
<span class="error" ng-show="EmailForm['email_'+$index].$touched && !EmailForm['email_'+$index].hasFocus">
<span ng-show="EmailForm['email_'+$index].$error.required">
Required
</span>
<span ng-show="EmailForm['email_'+$index].$error.email">
Invalid Email
</span>
<span ng-show="emailDel[$index]!='' && (emailDel | filter:emailDel[$index]:true).length>1">
Duplicate Email
</span>
</span>
</div>
</div>
</div>
<div class="col-md-4 col-md-offset-4">
<div class="col-md-10 col-md-offset-1">
<button type="submit" class="btn" ng-disabled="EmailForm.$invalid || (emailDel.length>1 && (emailDel | filter:'':true).length==emailDel.length)">Continue</button>
</div>
</div>
</div>
</div>
</form>
</div>
You can create your own directive for this.
When it loads you set focus to the $first element of your ngRepeat, when you starts to add elements, the focus should go to the $last.
Here's a snippet working:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.email = ['test1#gmail.com', 'test2#hotmail.com', 'test3#stackoverflow.com'];
$scope.init = true;
$scope.add = function() {
$scope.email.push('');
$scope.init = false;
}
})
.directive('setFocus', function() {
return {
scope: {
setFocus: '='
},
link: function(scope, element) {
if (scope.setFocus) element[0].focus();
}
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<form name="delEmailForm" novalidate accessible-form autocomplete="off" ng-submit="testing() && delEmailForm.$valid ? Add() :''">
<div class="col-md-6 col-md-offset-3 text-center" ng-repeat="e in email track by $index">
<input type="email" set-focus="init ? $first : $last" class="inputbox-text-left" placeholder="Email ID" validate-email ng-model="email[$index]" ng-required="email.length==1 " name="email_{{$index}}" id="email_{{$index}}">
</div>
<button type="button" value="add" ng-click="add()">+</button>
</form>
</body>
</html>

How to get input from user display in HTML page

I encounter a problem to display input from user into this table.
<tr ng-repeat="user in users" ng-class-even="'bg-light-grey'" ng-if="isLoading==false">
<td>
<div> {{user.username}} </div>
</td>
<td>
<div> {{user.name}} </div>
</td>
</tr>
If user click this "edit user" button, the form will appear.
<div class="glyphicon glyphicon-lock" ng-click="editUser();">
This is form that require user to fill edit their username and name
<div class="dialog-contents">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Edit User</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<form name="edituser">
<div class="form-group has-feedback" ng-class="editUser.username.$valid ? 'has-success' : 'has-error';">
<label class="col-sm-2 control-label" for="Username">Username</label>
<div class="col-sm-10">
<input type="username" ng-model="user.username" class="form-control" id="Username" placeholder="Enter Username"/>
</div>
<span class="glyphicon form-control-feedback"
ng-class="addUser.username.$valid ? 'glyphicon-ok' : 'glyphicon-remove';"></span>
</div>
<div class="form-group has-feedback" ng-class="editUser.name.$valid ? 'has-success' : 'has-error';">
<label class="col-sm-2 control-label" for="Name">Name</label>
<div class="col-sm-10">
<input type="name" ng-model="user.name" class="form-control" id="name" placeholder="Enter Name"/>
</div>
<span class="glyphicon form-control-feedback"
ng-class="addUser.name.$valid ? 'glyphicon-ok' : 'glyphicon-remove';"></span>
</div>
Form this form, if user click this "submit" button, the user details will appear in table as i provide the code above.
<button type="submit" class="btn btn-primary" ng-click="add();"
ng-class="isLoading ? 'disabled' : '';">Submit </button>
Now, i want to push the input from user, and display it in the table. But i am stuck in developing the controller to get the input and displayed it. Appreciate if someone can help solve this problem.
app.register('user', ['$scope', 'ngDialog', function ($scope, $dialog) {
$scope.isLoading = false;
$scope.addUser = function(){
$dialog.open({
showClose: false,
closeByEscape: true,
template: 'view/user/user-user-add.html',
controller: ['$scope', function ($dialogScope) {
$dialogScope.users = {
username : "" ,
name : "",
status : "",
}
.closePromise.then(function (data)
$dialogScope.hasError = false;
$dialogScope.errorMessage = '';
$dialogScope.add=function(){
$dialogScope.closeThisDialog({username:"xxx"});
}
}]
});
};
}]);
In your add function, close the dialog and pass the new user object to close promise, like this: -
//your dialog controller
$dialogScope.add=function(){
$dialogScope.closeThisDialog({username:"xxx"});
};
you main controller: -
$scope.addUser = function(){
$dialog.open({
....
})
.closePromise.then(function (data) {
console.log(data);
//check and find user from the data and do what you need, i.e. $scope.users.push(user);
});
};

Passing id in json through angular js

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')

Categories