How to get value of an input field inside a directive - javascript

I have a directive <stu-directive> with input field and a select in it. How do I get the values typed or selected in the directive function.
The html that uses my directive:
<div class="certFull">
<stu-directive obj ="certObj" ng-model="stuDirModel"></stu-directive>
<div class="addDir col-md-12 mg">
This is the directive's html:
<div ng-transclude class="container-fluid stuDirectiveClass mg">
<div class="rows">
<div class="col-md-12 mg">
<div class="form-group">
<div class="rows">
<div class="col-md-6"><label for="studentNameId">Student name</label></div>
<div class="col-md-6">
<select class="form-control" ng-model="selectStudent"> <!--get this value-->
<option>Stu1</option>
<option>Stu2</option>
<option>Stu3</option>
<option>Stu4</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group mg">
<div class="rows">
<div class="col-md-6"><label for="studentNameId">Student mark</label></div>
<div class="col-md-6">
<input type="text" class="form-control" ng-model="studentMark" placeholder="Student mark" /> <!--get this value-->
</div>
</div>
</div>
</div>
</div>
The directive function:
uiRouteApp.directive('stuDirective', function () {
return {
restrict: 'E',
//scope: {
// externalObj: '=obj'
//},
transclude: true,
templateUrl: 'htmlFiles/stuDirective.html',
link: function link(scope, element, attrs) {
//how do i access the input field values in directive
},
controller: ['$scope','$timeout', function ($scope,$timeout) {
console.log($scope.selectStudent); // undefined
}]
}
})

Always use . in ng-model
Define a variable in your directive then referance controller name before it in ng-model
uiRouteApp.directive('stuDirective', function () {
return {
restrict: 'E',
//scope: {
// externalObj: '=obj'
//},
transclude: true,
templateUrl: 'htmlFiles/stuDirective.html',
link: function link(scope, element, attrs) {
//how do i access the input field values in directive
},
controller: ['$scope','$timeout', function ($scope,$timeout) {
var stuDirectiveCtrl = this;
stuDirectiveCtrl.selectStudent = '';
stuDirectiveCtrl.log = function(){
console.log(this.selectStudent);
}
}],
controllerAs:'stuDirectiveCtrl'
}
})
<select class="form-control" ng-change="stuDirectiveCtrl.log()" ng-model="stuDirectiveCtrl.selectStudent"> <!--get this value-->
<option value="1">Stu1</option>
<option value="2">Stu2</option>
<option value="3">Stu3</option>
<option value="4">Stu4</option>
</select>
With usage of controllerAs you can referance your controller in html.

Man you haven't mentioned you directive in your html, also your directive is element based. you need to use your directive as element in html.
Please go through with these link might help you.
https://www.w3schools.com/angular/angular_directives.asp
https://docs.angularjs.org/guide/directive
See code snippet i am able to get the element in directive.
var app = angular.module('app', function() {});
app.directive('stuDirective', function () {
return {
restrict: 'E',
transclude: true,
//templateUrl: 'htmlFiles/stuDirective.html',
link: function link(scope, element, attrs) {
scope.Details = function(){
console.log(scope.selectStudent + ' ' +scope.studentMark);
};
},
controller: ['$scope','$timeout', function ($scope,$timeout) {
}]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="certFull" ng-app="app">
<stu-directive obj ="certObj" ng-model="stuDirModel"></stu-directive>
<div class="container-fluid">
<div class="rows">
<div class="col-md-12 mg">
<div class="form-group">
<div class="rows">
<div class="col-md-6"><label for="studentNameId">Student name</label></div>
<div class="col-md-6">
<select class="form-control" ng-model="selectStudent"> <!--get this value-->
<option>Stu1</option>
<option>Stu2</option>
<option>Stu3</option>
<option>Stu4</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group mg">
<div class="rows">
<div class="col-md-6"><label for="studentNameId">Student mark</label></div>
<div class="col-md-6">
<input type="text" class="form-control" ng-model="studentMark" placeholder="Student mark" /> <!--get this value-->
</div>
<div class="col-md-6">
<button ng-click="Details()">Call Dir</button>
</div>
</div>
</div>
</div>
</div>
<div class="addDir col-md-12 mg">

You need some event like this: (or if you do not want to use event then use $watch)
var app = angular.module('app', function() {});
app.directive('stuDirective', function () {
return {
restrict: 'E',
transclude: true,
//templateUrl: 'htmlFiles/stuDirective.html',
link: function link(scope, element, attrs) {
scope.Print = function(){
console.log(scope.selectStudent + ' ' +scope.studentMark);
};
},
controller: ['$scope','$timeout', function ($scope,$timeout) {
}]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="certFull" ng-app="app">
<stu-directive obj ="certObj" ng-model="stuDirModel"></stu-directive>
<div class="container-fluid">
<div class="rows">
<div class="col-md-12 mg">
<div class="form-group">
<div class="rows">
<div class="col-md-6"><label for="studentNameId">Student name</label></div>
<div class="col-md-6">
<select class="form-control" ng-model="selectStudent"> <!--get this value-->
<option>Stu1</option>
<option>Stu2</option>
<option>Stu3</option>
<option>Stu4</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group mg">
<div class="rows">
<div class="col-md-6"><label for="studentNameId">Student mark</label></div>
<div class="col-md-6">
<input type="text" class="form-control" ng-model="studentMark" placeholder="Student mark" /> <!--get this value-->
</div>
<div class="col-md-6">
<button ng-click="Print()">Call Dir</button>
</div>
</div>
</div>
</div>
</div>
<div class="addDir col-md-12 mg">

Into HTML you have to use your directive as element and add to it an attribute that contain the value you should use into directive, for example:
<stu-directive selected="selectStudent"></stud-directive>
Directive should use scope for save the value, for example:
uiRouteApp.directive('stuDirective', function () {
return {
restrict: 'E',
scope: {
selected: '='
},
transclude: true,
templateUrl: 'htmlFiles/stuDirective.html',
link: function link(scope, element, attrs) {
console.log(scope.selected);
}]
}

angular.module("myApp",[])
.directive('stuDirective', function () {
return {
restrict: 'E',
scope:{
selectStudent:'#',
studentMark:'#'
},
template: '<div class="container-fluid stuDirectiveClass mg"><div class="rows"><div class="col-md-12 mg"><div class="form-group"><div class="rows"><div class="col-md-6">label for="studentNameId">Student name</label></div> <div class="col-md-6"><select class="form-control" ng-model="selectStudent"><option>Stu1</option> <option>Stu2</option><option>Stu3</option> <option>Stu4</option></select></div></div></div></div><div class="col-md-12"><div class="form-group mg"><div class="rows"> <div class="col-md-6"><label for="studentNameId">Student mark</label></div><div class="col-md-6"><input type="text" class="form-control" ng-model="studentMark" placeholder="Student mark" /></div></div></div></div></div>',
link: function link(scope, element, attrs) {
},
controller: function ($scope,$timeout) { $scope.$watch('[studentMark,selectStudent]',function(value,value1){
console.log(value)
console.log(value1)
})
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body ng-app="myApp">
<stu-directive></stu-directive>
</body>
</html>

Related

Using Bootstrap grid in angularjs components

What I'm basically trying to do is wrap grid element divs into angular components. The effort is to reduce typing strokes and get a standard for inputs:
<bootstrap-row>
<bootstrap-input-text col=6 ng-model="$ctrl.model" label="hey!">
</bootstrap-row>
Which would render something like the following
<div class="row">
<div class="col-md-6">
<label>hey!</label>
<input type="text" ng-model="$ctrl.model">
</div>
</div>
It works, kind of. The javascript works fine with the model binding, it's just that the CSS gets mangled. I have a codeopen here: https://codepen.io/anon/pen/JmxmoY?editors=1111
It has something to do with how the browser renders the <bootstrap-input-text> in between the row div and the column div. If I open up dev tools and inspect the difference between <bootstrap-row> and <bootstrap-input-text>, there are none. Is there a way around this or am I SOL?
Try this one
.component('bootstrapColumn', {
bindings: {
column: "#"
},
transclude: true,
template: function ($element, $attrs) {
$element.addClass('col-md-' + $attrs.column);
return '<div ng-transclude></div>';
}
})
Are you trying to apply a specific solution with components?
Cause you can try this as a Directive
.directive('bootstrapCol', function () {
return {
restrict: 'EAC',
scope: {
column: '#'
},
link: function (scope, element) {
var tc = 'col-md-' + scope.column;
element.addClass(tc);
}
}
})
It gives you plenty of properties either use it in your custom component
<bootstrap-row>
<bootstrap-col column="4">
<label>Input 5</label>
<input type="text" class="form-control">
</bootstrap-col>
<div class="bootstrap-col" column="4">
<label>Class</label>
<input type="text" class="form-control">
</div>
<div bootstrap-col column="4">
<label>Property</label>
<input type="text" class="form-control">
</div>
</bootstrap-row>
(function () {
'use strict';
angular
.module('test', [])
.component('bootstrapRow', {
transclude: true,
template: '<div class="row" ng-transclude></div>'
})
.component('bootstrapColumn', {
bindings: { column: "#"},
transclude: true,
template: function ($element, $attrs) {
$element.addClass('col-md-' + $attrs.column);
return '<div ng-transclude></div>';
}
}).directive('bootstrapCol', function () {
return {
restrict: 'EAC',
scope: { column: '#' },
link: function (scope, element) {
var tc = 'col-md-' + scope.column;
element.addClass(tc);
}
};
});
})();
<html>
<head>
<title>fun with bootstrap and elements</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
</head>
<body ng-app="test">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Input 1</label>
<input type="text" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Input 2</label>
<input type="text" class="form-control">
</div>
</div>
</div>
<bootstrap-row>
<bootstrap-column column="6">
<div class="form-group">
<label>Input 3</label>
<input type="text" class="form-control">
</div>
</bootstrap-column>
<bootstrap-column column="6">
<div class="form-group">
<label>Input 4</label>
<input type="text" class="form-control">
</div>
</bootstrap-column>
</bootstrap-row>
<bootstrap-row>
<bootstrap-col column="4">
<div class="form-group">
<label>Element-As Component</label>
<input type="text" class="form-control">
</div>
</bootstrap-col>
<div class="bootstrap-col" column="4">
<div class="form-group">
<label>Class</label>
<input type="text" class="form-control">
</div>
</div>
<div bootstrap-col column="4">
<div class="form-group">
<label>Property</label>
<input type="text" class="form-control">
</div>
</div>
</bootstrap-row>
</div>
</body>
</html>
<div class="row" ng-controller="PortfolioCtrl">
<div class="col-lg-4 col-md-4 col-sm-6 mb-3" ng-repeat-start="stuff in profile track by $index">
<div class="card">
<div class="card-header">
{{stuff.name}}
</div>
<div class="card-body">
<h5 class="card-title">{{stuff.title}}</h5>
<p class="card-text text-justify">{{stuff.desc}}</p>
</div>
</div>
</div>
<div ng-repeat-end>
<div class="clearfix visible-lg-block" ng-if="($index+1) % 6 == 0"></div>
<div class="clearfix visible-md-block" ng-if="($index+1) % 3 == 0"></div>
<div class="clearfix visible-sm-block" ng-if="($index+1) % 2 == 0"></div>
</div>
</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>

dxSelectBox inside Angularjs ui modal, the option list not showing up

I am using $uibModal.open({}) as create form. Inside the modal controller I originally have a select box in AngularJS which is working fine.
html
<div class="container">
<form name="genQForm" novalidate ctrl-generate-submit-key="submitForm(genQForm.$valid, qbeventInfo)">
<div class="row">
<div class="col-lg-6 col-md-7 col-sm-8 col-xs-8 pull-md-left" style="margin-top:10px;">
<h4>{{ formHeader }}</h4>
<hr style="margin:5px 0 15px 0;" />
</div>
<div id="form-validation" class="text-danger"></div>
</div>
<!-- ROW 1 : Event -->
<div class="row form-group">
<div class="col-lg-6 col-md-7 col-sm-8 col-xs-8 pull-md-left">
<label for="eventID" class="col-lg-4 col-md-4 col-sm-8 col-xs-8 control-label">Event</label>
<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12" ng-class="{ 'has-error' : genQForm.eventID.$invalid && !genQForm.eventID.$pristine }">
<select id="eventID" name="eventID"
ng-model="qbeventInfo.eventID"
ng-change="eventchange()" required>
<option value="{{item.eventID}}"
ng-repeat="item in eventLists">
{{item.title}}
</option>
</select>
</div>
</div>
</div>
<!-- Submit Button -->
<div class="row" style="padding-bottom: 10px;">
<div class="form-group">
<div class="col-md-10">
<button type="submit"
ng-show="isformButton" class="btn btn-light-green" xng-disabled="genQForm.$invalid" tabindex="6"
ng-click="submitForm(genQForm.$valid, qbeventInfo)">
<span id="gensubmitBtn">{{formButton}}</span>
</button>
<button class="btn btn-light-red" ng-click="cancel()" tabindex="7">Cancel</button>
</div>
</div>
</div>
In my Angular Controller, the $scope.eventLists is taken from
app.controller.js
task.getOpenEvent() // this function is created from app.service
.then(function (result) {
console.info('open event lists :', result.data);
$scope.eventLists = result.data;
});
-- Modal is open by using
$uibModal.open({
templateUrl: "pages/common/header/generateQ.html",
size: size,
scope: $scope,
controller: function ($uibModalInstance, $scope, $window, task, $route) { ...
app.service.js
task.getOpenEvent = function () {
var defer = $q.defer();
$http.get(ev_service_url + '/0/openevent')
.then(function (response) {
// Success
defer.resolve(response);
}, function (err, status) {
// Error
defer.reject(err);
});
return defer.promise;
}
I am trying to replace this select box with dxSelectBox devexpress style.
<div dx-select-box="{dataSource: eventLists,
placeholder: 'Event Name',
valueExpr: 'eventID',
displayExpr: 'title'
}" >
</div>
I followed the format from the devexpress tutorial. I can see the placeholder, bUt option list is empty.
Why the option lists is not showing up when used in DevExpress dxSelectBox?
Try to wrap the dxSelectBox dataSource option into bindingOptions:
<div dx-select-box="{
bindingOptions: {
dataSource: 'eventLists'
},
// other options
}"></div>

angularJs - directive scope variable not binding

I have a binding problem with one of my directives that is causing me problems. Usually I don't have problems with binding but I can't see the bug. I have this directive:
radioMenuDirective.js
(function () {
"use strict";
var myAppModule = angular.module('myApp');
myAppModule.directive('radioMenuAllocateSection', function () {
return {
templateUrl: 'Scripts/app/shared/radiomenu/tmplAllocateSection.html',
restrict: 'E',
scope: {
allocatedTo: '='
},
controller: [
'$scope', 'genericService', function ($scope, genericService) {
$scope.radio = {
name: 'department'
};
}
],
}
});
})();
tmplAllocateSection.html
<label>Allocate Section To:</label>
<br/>
<form name="myForm" ng-controller="ExampleController" class="form-inline">
<div class="form-group">
<label>
<input type="radio" ng-model="radio.name" value="department">
Department
</label>
<label>
<input type="radio" ng-model="radio.name" value="user">
User
</label>
<div ng-if="radio.name == 'department'">
{{allocatedTo}}
<department-dropdown department="allocatedTo"></department-dropdown>
</div>
<div ng-if="radio.name == 'user'">
{{allocatedTo}}
<user-dropdown user="allocatedTo"></user-dropdown>
</div>
</div>
</form>
I can see the scope variable within my directive with
{{allocatedTo}}
However above this directive is another 1
tmplSectionCategories.html
<form role="form" name="frmContactDetails">
the enquiry data: {{enquiryData.selectedPersonOrDep}}
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Section Categories:</h3>
</div>
<h6>
<div class="panel-body">
<div class="form-group col-md-6 ignore-left-padding">
<subject-topic-dropdown selected-subject="enquiryData.subject" selected-topic="enquiryData.topic"></subject-topic-dropdown>
<keywords-dropdown selected-subject="enquiryData.subject"></keywords-dropdown>
<div class="form-group col-md-12 ignore-left-padding">
<genus-dropdown selected-genus="enquiryData.genus"></genus-dropdown>
</div>
<plant-names-dropdown selected-plant="enquiryData.plant"></plant-names-dropdown>
</div>
<div class="form-group col-md-6 ignore-left-padding">
<department-keyword-dropdown selected-department="enquiryData.department" selected-keyword="enquiryData.keyword"></department-keyword-dropdown>
<div class="form-group col-md-12 ignore-left-padding">
<label class="col-md-12 control-label ignore-left-padding">Quantity:</label>
<div class="col-md-8 ignore-left-padding">
<div class="col-md-2 ignore-left-padding">
<input type="number" ng-model="enquiryData.quantity" class="form-control input-sm" style="width: 50px" min="0" />
</div>
</div>
</div>
<radio-menu-allocate-section allocated-to="enquiryData.selectedPersonOrDep"></radio-menu-allocate-section>
</div>
</div>
</h6>
</div>
</div>
</form>
Directive declared on page
<radio-menu-allocate-section allocated-to="enquiryData.selectedPersonOrDep"></radio-menu-allocate-section>
</div>
{{enquiryData.selectedPersonOrDep}}
This doesn't show anything when the dropdown changes, so I have a problem where I don't have the value after selecting a value. I need it above for a button click handler.

how to add data using angularjs

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

Categories