I am designing the simple page which will take the start and end date from the user,validate it and post it.
Below is my HTML code,
<body>
<div ng-app="appTable">
<div ng-controller="Allocation">
Select start date:
<input type="text"
datepicker
ng-model="start_date" />
<br>
<br>
Select end date:
<input type="text"
datepicker
ng-model="end_date" />
<br>
<br>
<button ng-click="Submit()"> Submit </button>
{{msg}}
{{test1}}
{{test2}}
</div>
</div>
</body>
Below is the aj script:
<script>
var app = angular.module("appTable", []);
app.controller("Allocation", function($scope) {
$scope.start_date = "2017-05-01";
$scope.end_date = "2017-05-19";
$scope.Submit = function() {
var start = new Date($scope.start_date);
var end = new Date($scope.end_date);
if (start > end) {
$scope.msg = "Start date must be less than the end date."
} else {
$scope.msg = "";
$scope.test = "";
$scope.postData($scope.start_date, $scope.end_date);
}
};
$scope.postData = function(s_date, e_date) {
var data = {
s_date: s_date,
e_date: e_date,
};
$scope.test1 = "Post called 1";
$http.post('/view_status/', data).then(function(response) {
$scope.test2 = "Post called 2";
if (response.data)
$scope.msg = "Post Data Submitted Successfully!";
}, function(response) {
$scope.msg = "Service not Exists";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
app.directive("datepicker", function() {
function link(scope, element, attrs, controller) {
// CALL THE "datepicker()" METHOD USING THE "element" OBJECT.
element.datepicker({
onSelect: function(dt) {
scope.$apply(function() {
// UPDATE THE VIEW VALUE WITH THE SELECTED DATE.
controller.$setViewValue(dt);
});
},
dateFormat: "yy-mm-dd" // SET THE FORMAT.
});
}
return {
require: 'ngModel',
link: link
};
});
</script>
For the debugging purpose I have taken the 2 flags test1,test2 which will print the message before and after the call of the POST service.
Flag test1 is printing the message but test2,msg are not printing anything.
Please help if I am missing something.
Inject $http to your controller to access $http.post.
like: app.controller("Allocation", function($scope, $http) {
You need to inject $http into your controller
Related
I have the following code and I have tried just bout everything to return a promise that would work with the directive. I have even tried returning the response data and return $q.when(data) and nothing. Ive tried reading on promises and this one is a bit different then Ive read. Something I'm missing?
myApp.controller('smsCtrl', function($scope){
$scope.sendSMS = function(){
let sms = {'number': $scope.number ,'message': $scope.message};
serviceNameHere.sendSMS(sms).then(function(response){
$scope.smsSuccessMsg = "Message Sent Successfully";
}, function(response){
$scope.smsErrorMsg = response.data['message'];
});
};
})
myApp.directive('onClickDisable', function() {
return {
scope: {
onClickDisable: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
element.prop('disabled',true);
scope.onClickDisable().finally(function() {
element.prop('disabled',false);
})
});
}
};
});
The following html
<div ng-controller="smsCtrl">
<-- field inputs here --></-->
<button type="button" class="btn btn-primary" on-click-disable="sendSMS()">SEND</button>
</div>
JSfiddle Example
There is no need to have a special directive for this. Simply use ng-disabled and ng-click:
<div ng-controller="smsCtrl">
<!-- field inputs here -->
<button ng-click="sendSMS()" ng-disabled="pendingSMS">
SEND
</button>
</div>
In the controller:
myApp.controller('smsCtrl', function($scope, serviceNameHere){
$scope.sendSMS = function(){
let sms = {'number': $scope.number ,'message': $scope.message};
$scope.pendingSMS = true;
serviceNameHere.sendSMS(sms).then(function(response){
$scope.smsSuccessMsg = "Message Sent Successfully";
}, function(response){
$scope.smsErrorMsg = response.data['message'];
}).finally(function() {
$scope.pendingSMS = false;
});
};
})
When the SMS message starts, the controller sets the pendingSMS flag to disable the Send button. When the service completes, the flag is reset and the button is re-enabled.
I would like to access the input field value inside a variable that could be used in AngularJS so that I could add it to a string with the help of which I could call a rest api.
kindly help.
<body ng-app="myApp">
<div ng-controller="myCtr">
<form name="myForm">
<input type="text" ng-model='pinCode' id="zip" onBlur="myZipcode">
{{city}}
{{state}}
</form>
</div>
<script>
var zip;
var pat1;
function myZipcode(){
zip = document.getElementById("zip").value;
pat1 = 'http://ziptasticapi.com/'+zip;
}
var myApp = angular.module('myApp' , []);
myApp.controller('myCtr', function($scope, $http){
var path = 'http://ziptasticapi.com/12345'
$http.get(pat1).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;});
});
</script>
</body>
Here in http.get service if I use path variable instead of pat1 it works.
Another thing that I want the state and city to come dynamically without the form to be submitted and to be called from an REST API. That is why I am trying to get the input value inside a variable to accomplish the task
No need to define extra var for pinCode because of you used ng-model so you can access pinCode from your controller. Also should use ng-blur instead of onBlur.
You can use like
HTML:
<input type="text" ng-model='pinCode' id="zip" ng-blur="myZipcode()">
Controller:
var myApp = angular.module('myApp' , []);
myApp.controller('myCtr', function($scope, $http){
$scope.pinCode= ''; // defaulr empty
var path = 'http://ziptasticapi.com/';
$scope. myZipcode = function() {
$http.get(path + $scope.pinCode).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;
});
};
});
You should not access html elements from your controller code. Angular's two way data-binding already transfers the form input's value into the $scope.pinCode variable. So you only need some action to trigger your server call. See this sample in the angular docs: https://docs.angularjs.org/api/ng/directive/ngSubmit
myApp.controller('myCtr', function($scope, $http) {
$scope.doCall = function() {
// $scope.pinCode() is set here
$scope.$http.get(...).then(
function(response) {
$scope.city = response.data.city; // or similar
}
);
}
});
just bind zip and pat1 on controller's scope
Controller:
myApp.controller('myCtr', function($scope, $http){
$scope.zip = document.getElementById("zip").value || 0;
$scope. pat1 = 'http://ziptasticapi.com/'+ $scope.zip || '';
$scope.myZipcode();
});
and then in zipcode
Zipcode function:
$scope.myZipcode = function myZipcode(){
$scope,zip = document.getElementById("zip").value;
$scop.pat1 = 'http://ziptasticapi.com/'+zip;
$http.get(pat1).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;}
}
Complete code:
<body ng-app="myApp">
<div ng-controller="myCtr">
<form name="myForm">
<input type="text" ng-model='pinCode' id="zip" ng-blur="myZipcode">
{{city}}
{{state}}
</form>
</div>
<script>
myApp.controller('myCtr', function($scope, $http){
$scope.zip = document.getElementById("zip").value || 0;
$scope. pat1 = 'http://ziptasticapi.com/'+ $scope.zip || '';
$scope.myZipcode();
$scope.myZipcode = function myZipcode(){
$scope,zip = document.getElementById("zip").value;
$scop.pat1 = 'http://ziptasticapi.com/'+zip;
$http.get(pat1).success(function (response) {
$scope.city = response.city;
$scope.state = response.state;}
}
});
</script>
</body>
i am having a problem with ng-model .When i am adding tag from suggestion list its not updating model value until i am not deleting tags and adding again.In my project its working fine but for plunker only its happening.Please check this out and help me..
thank you..
Here is my html:-
<tags-input ng-model="tags2" display-property="tagName" on-tag-added="getTags()" id="target">
<auto-complete source="loadTags($query)" min-length="2"></auto-complete>
</tags-input>
<p>{{tags2}}</p>
Here is my js:-
var app = angular.module('myApp', ['ngTagsInput', 'ui.bootstrap']);
app.controller(
'myController',
function($scope, $http) {
$scope.tagsValues =[];
$scope.loadTags = function(query) {
return $http.get('tags.json');
};
$scope.getTags = function() {
$scope.tagsValues = $scope.tags2.map(function(tag) {
return tag.tagId;
});
alert(" Tag id is :"+ $scope.tagsValues);
};
});
Here is my plunker:-
http://plnkr.co/edit/6Mr2qk2S2RvGJLevf2UI?p=preview
All you have to do to make this work, is define and initialize the variable $scope.tags2 first:
var app = angular.module('myApp', ['ngTagsInput', 'ui.bootstrap']);
app.controller(
'myController',
function($scope, $http) {
$scope.tagsValues = '';
$scope.tags2 = [];
$scope.loadTags = function(query) {
return $http.get('tags.json');
};
$scope.getTags = function() {
$scope.tagsValues = $scope.tags2.map(function(tag) {
return tag.tagId;
});
alert(" Tag id is :"+ $scope.tagsValues);
};
});
See my plunker: http://plnkr.co/edit/Y3f8kLBnexOXg5gwmldL?p=preview
I would like to make a custom datepicker directive with a custom template.
But I have no idea how to start building it...
How to include date data for my directive?
I appreciate your guide or give me some advice to work on this more precisely.
It might help you! follow the below steps
HTML code sample:
<label>Birth Date</label>
<input type="text" ng-model="birthDate" date-options="dateOptions" custom-datepicker/>
<hr/>
<pre>birthDate = {{birthDate}}</pre>
<script type="text/ng-template" id="custom-datepicker.html">
<div class="enhanced-datepicker">
<div class="proxied-field-wrap">
<input type="text" ui-date-format="yy-mm-dd" ng-model="ngModel" ui-date="dateOptions"/>
</div>
<label>
<button class="btn" type="button"><i class="icon-calendar"></i></button>
<span class="datepicker-date">{{ngModel | date:'d MMM yyyy'}}</span>
</label>
</div>
</script>
JS code sample:
angular
.module('App',['ui.date'])
.directive('customDatepicker',function($compile){
return {
replace:true,
templateUrl:'custom-datepicker.html',
scope: {
ngModel: '=',
dateOptions: '='
},
link: function($scope, $element, $attrs, $controller){
var $button = $element.find('button');
var $input = $element.find('input');
$button.on('click',function(){
if($input.is(':focus')){
$input.trigger('blur');
} else {
$input.trigger('focus');
}
});
}
};
})
.controller('myController',function($scope){
$scope.birthDate = '2013-07-23';
$scope.dateOptions = {
minDate: -20,
maxDate: "+1M +10D"
};
});
/*global angular */
/*
jQuery UI Datepicker plugin wrapper
#note If ≤ IE8 make sure you have a polyfill for Date.toISOString()
#param [ui-date] {object} Options to pass to $.fn.datepicker() merged onto uiDateConfig
*/
angular.module('ui.date', [])
.constant('uiDateConfig', {})
.directive('uiDate', ['uiDateConfig', '$timeout', function (uiDateConfig, $timeout) {
'use strict';
var options;
options = {};
angular.extend(options, uiDateConfig);
return {
require:'?ngModel',
link:function (scope, element, attrs, controller) {
var getOptions = function () {
return angular.extend({}, uiDateConfig, scope.$eval(attrs.uiDate));
};
var initDateWidget = function () {
var showing = false;
var opts = getOptions();
// If we have a controller (i.e. ngModelController) then wire it up
if (controller) {
// Set the view value in a $apply block when users selects
// (calling directive user's function too if provided)
var _onSelect = opts.onSelect || angular.noop;
opts.onSelect = function (value, picker) {
scope.$apply(function() {
showing = true;
controller.$setViewValue(element.datepicker("getDate"));
_onSelect(value, picker);
element.blur();
});
};
opts.beforeShow = function() {
showing = true;
};
opts.onClose = function(value, picker) {
showing = false;
};
element.on('blur', function() {
if ( !showing ) {
scope.$apply(function() {
element.datepicker("setDate", element.datepicker("getDate"));
controller.$setViewValue(element.datepicker("getDate"));
});
}
});
// Update the date picker when the model changes
controller.$render = function () {
var date = controller.$viewValue;
if ( angular.isDefined(date) && date !== null && !angular.isDate(date) ) {
throw new Error('ng-Model value must be a Date object - currently it is a ' + typeof date + ' - use ui-date-format to convert it from a string');
}
element.datepicker("setDate", date);
};
}
// If we don't destroy the old one it doesn't update properly when the config changes
element.datepicker('destroy');
// Create the new datepicker widget
element.datepicker(opts);
if ( controller ) {
// Force a render to override whatever is in the input text box
controller.$render();
}
};
// Watch for changes to the directives options
scope.$watch(getOptions, initDateWidget, true);
}
};
}
])
.constant('uiDateFormatConfig', '')
.directive('uiDateFormat', ['uiDateFormatConfig', function(uiDateFormatConfig) {
var directive = {
require:'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var dateFormat = attrs.uiDateFormat || uiDateFormatConfig;
if ( dateFormat ) {
// Use the datepicker with the attribute value as the dateFormat string to convert to and from a string
modelCtrl.$formatters.push(function(value) {
if (angular.isString(value) ) {
return jQuery.datepicker.parseDate(dateFormat, value);
}
return null;
});
modelCtrl.$parsers.push(function(value){
if (value) {
return jQuery.datepicker.formatDate(dateFormat, value);
}
return null;
});
} else {
// Default to ISO formatting
modelCtrl.$formatters.push(function(value) {
if (angular.isString(value) ) {
return new Date(value);
}
return null;
});
modelCtrl.$parsers.push(function(value){
if (value) {
return value.toISOString();
}
return null;
});
}
}
};
return directive;
}]);
Here is a working fiddle http://jsfiddle.net/FVfSL/.
A bit confused with binding...
How to properly bind values from input fields to textarea?
app.controller('MainCtrl', function($scope) {
$scope.hello = 'Hello';
$scope.world = 'World!'
//this template comes from json
$scope.fromjson = "{{hello}} {{world}} and have a good time";
//this template comes from json
});
And a simple body:
<body ng-controller="MainCtrl">
<input ng-model="hello">
<input ng-model="world">
<helloworld></helloworld>
</body>
A have to edit my miserable example because your
kindly answers didn't solve my problem.
I had plenty of unique texts - letter templates in which some fields should be filled by user. There are ten fields occuring conditionally depending of text selected.
text1: "Blah, blah {{field.first}}.blah {{filed.second}}"
text2: "{{field.third}} blah, blah {{field.first}}"
text3: "Blah, blah {{field.fourth}}"
and so on...
Texts are stored in database and obtained through JSON
function(textid) {
$http.get('json/json.php',
{ params: { id: textid } }).
success(function(data, status, headers, config) {
$scope.SelectedText = data;
})
};
I organized it in one form with all ten input fields, visible depending of
selected text.
Completed/filled template should be visible in textarea at the bottom of form to be copied to another place.
Should I change the way I store the templates?
or back to question is there any other way the fields could be inserted into view ?
I think what you need is $interpolate service and $scope.$watch take a look at this jsfiddle :
http://jsfiddle.net/michal_taborowski/6u45asg9/
app.controller('MainCtrl', function($scope,$interpolate) {
$scope.hello = 'Hello';
$scope.world = 'World!';
//this template comes from json
$scope.template = " {{hello}} {{world}} and have a good time";
//this template comes from json
var updateTemplate = function(oldVal,newVal,scope){
scope.fromjson = $interpolate(scope.template)(scope);
}
$scope.$watch('hello', updateTemplate );
$scope.$watch('world', updateTemplate );
});
Of course you should move $watch to link function in your directive and pass hello and world as scope variable to this directive - this is just a quick example how you can do it.
I think that what you want is this:
app.controller('MainCtrl', function($scope) {
$scope.hello = 'Hello';
$scope.world = 'World!'
//this template comes from json
$scope.fromjson = function(){
return $scope.hello + " " + $scope.world + " and have a good time";
};
});
app.directive('helloworld', function() {
return {
restrict: 'E',
template: '<textarea>{{fromjson()}}</textarea>'
};
});
Example here: http://plnkr.co/edit/8YrIjeyt9Xdj2Cf7Izr5?p=preview
The problem with your code is that when you declare $scope.fromjson = "{{hello}} {{world}} and have a good time" you are not binding anything, you are just assiging that string to the fromjson property.
EDIT:
As HeberLZ pointed out in the comment bellow, it would be much more efficient to do this instead:
app.controller('MainCtrl', function($scope) {
$scope.hello = 'Hello';
$scope.world = 'World!'
});
app.directive('helloworld', function() {
return {
restrict: 'E',
template: '<textarea>{{ hello + " " + world + " and have a good time"}}</textarea>'
};
});
One way would be something like this:
Controller:
app.controller('MainCtrl', function($scope) {
$scope.hello = 'Hello';
$scope.world = 'World!'
});
Directive:
app.directive('helloworld', function($http) {
return {
restrict: 'E',
scope: {
'hello': '=',
'world': '='
},
link: function(scope){
scope.jsonFromServer = '';
$http.get('someUrl').then(function(response){
scope.jsonFromServer = response.data;
});
var updateFromjson = function(){
scope.fromjson = scope.hello + ' ' + scope.world + ' ' + scope.jsonFromServer;
}
scope.$watch('hello', updateFromjson);
scope.$watch('world', updateFromjson);
}
template: '<textarea>{{fromjson}}</textarea>'
};
});
Body:
<body ng-controller="MainCtrl">
<input ng-model="hello">
<input ng-model="world">
<helloworld hello="hello" world="world"></helloworld>
</body>
app.controller('MainCtrl', function($scope) {
$scope.hello = 'Hello';
$scope.world = 'World!'
//this template comes from json
$scope.aDiffFunc = function() {
return $scope.hello + " " + $scope.world + " and have a good time";
};
//this template comes from json
});
app.directive('helloworld', function() {
return {
restrict: 'E',
template: '<textarea>{{aDiffFunc()}}</textarea>'
};
});
this should be it??
http://plnkr.co/edit/ygA4U0v7fnuIbqAilrP7?p=preview