This is my HTML form
<form ng-submit='create()'>
..
.
.
<input type='file' ng-model='logo' accept="image/*">
</form>
this is my controller :
$scope.create = function () {
$scope.Ent = {}
$scope.Ent.logo = $scope.logo;
ng-model won't work in input type 'file. use a custom directive to bind it
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
assign scope variable to fileread attribute
<form ng-submit='create()'>
..
.
.
<input type='file' fileread='logo' accept="image/*">
</form>
Related
` ~ ! # # $ % ^ & * ( ) _ + = { } | [ ] \ : ' ; " < > ? , . /
I want to restrict the above mentioned special characters and numbers in the input text field. I used the
ng-pattern="/^[a-zA-Z ]*$/"
to restrict the special characters. This pattern is blocking all the special characters. I am facing issue when I want to enter name "PĂ©rez Gil" I don't want to restrict other language text.
Updates:
I think $parsers is the best options here. See the updated code and plunker.
Controller
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
}])
.directive('myDirective', function() {
function link(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
var reg = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
// if view values matches regexp, update model value
if (viewValue.match(reg)) {
return viewValue;
}
// keep the model value as it is
var transformedValue = ngModel.$modelValue;
ngModel.$setViewValue(transformedValue);
ngModel.$render();
return transformedValue;
});
}
return {
restrict: 'A',
require: 'ngModel',
link: link
};
});
Template
<input type="text" ng-model="model" id="input" name="input" my-directive />
Here's a updated example on Plunker
https://plnkr.co/edit/eEOJLi?p=preview
Old Answers:
Since you already have a list of characters that you want to restrict, you can spell them out in the ng-pattern expression like:
Controller
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
}]);
Template
<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" />
Here's a working example on Plunker
https://plnkr.co/edit/eEOJLi?p=preview
Use Directives to restrict Special characters:
angular.module('scPatternExample', [])
.controller('scController', ['$scope', function($scope) {
}])
.directive('restrictSpecialCharactersDirective', function() {
function link(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
var reg = /^[a-zA-Z0-9]*$/;
if (viewValue.match(reg)) {
return viewValue;
}
var transformedValue = ngModel.$modelValue;
ngModel.$setViewValue(transformedValue);
ngModel.$render();
return transformedValue;
});
}
return {
restrict: 'A',
require: 'ngModel',
link: link
};
});
In Html:
<input type="text" ng-model="coupon.code" restrict-Special-Characters-Directive>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" ng-change="Check(myValue)" ng-model="myValue" />
<p ng-show="test">The Special Character not accept.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope,ngModel) {
$scope.Check= function(x) {
var reg = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./]*$/;
if (!x.match(reg)) {
$scope.myValue = x.substring(0, x.length-1);
$scope.test=true;
}
else
{
$scope.test=false;
}
};
}]);
</script>
</body>
</html>
I have written a directive by using typescript. here is my directive below.
'use strict';
module App.Directives {
interface IPageModal extends ng.IDirective {
}
interface IPageModalScope extends ng.IScope {
}
class PageModal implements IPageModal {
static directiveId: string = 'pageModal';
restrict: string = "A";
constructor(private $parse: ng.IParseService) {
}
link = (scope: IPageModalScope, element, attrs) => {
element.click((event) => {
event.preventDefault();
var options = {
backdrop: 'static',
keyboard: false
};
event.openModal = function () {
$('#' + attrs['targetModal']).modal(options);
};
event.showModal = function () {
$('#' + attrs['targetModal']).modal('show');
};
event.closeModal = function () {
$('#' + attrs['targetModal']).modal('hide');
};
var fn = this.$parse(attrs['pageModal']);
fn(scope, { $event: event });
});
}
}
//References angular app
app.directive(PageModal.directiveId, ['$parse', $parse => new PageModal($parse)]);
}
Use in HTML
<button class="btn blue-grey-900" target-modal="emplpyeeViewModal" page-modal="vm.addEmployee($event)">
<i class="icon-plus m-b-xs"></i>
</button>
Use in Controller
addEmployee($event) {
$event.openModal();
};
This line does not work. var fn = this.$parse(attrs['pageModal']); . I can not understand what is wrong. The error is
this.$parse is undefined.
and Service is called two times
It's quite trivial: your this is not your class'es scope because the function openmodal(event) { defines its own.
Declare the function on a class level or use arrow function instead, e.g.
link = (scope: IPageModalScope, element, attrs) => {
element.click((event) => {
event.preventDefault();
var options = {
backdrop: 'static',
keyboard: false
};
event.openModal = function () {
$('#' + attrs['targetModal']).modal(options);
};
event.showModal = function () {
$('#' + attrs['targetModal']).modal('show');
};
event.closeModal = function () {
$('#' + attrs['targetModal']).modal('hide');
};
var fn = this.$parse(attrs['pageModal']);//does not work here
fn(scope, { $event: event });
});
}
I have a input type= number field.It allows whole number and decimal number.But I need only whole number to be enter in the input.I have created a directive which is working only for input type=text,not working for input type=number.The reason is I need a number keyboard in mobile.
Below code is for number only,
Angularjs :
.directive('numbersOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9-]/g, '');
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return '';
}
ngModelCtrl.$parsers.push(fromUser);
}
};
})
Html:
<input type="number" ng-model="points" numbers-only required>
Any suggestions welcome
Try this
html
<input type="text" ng-model="myText" name="inputName" numbers-only>
directive
myApp.directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'').replace('.','') : null;
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
https://jsfiddle.net/vorant/Lzw0yoma/
I need to show a model popup window in a button click.can any one suggest the best method to achieve this in angularjs without BootstrpJS?
I tried the below and is not working. :(
html
<div>
<button ng-click='toggleModal()'>Add Dataset</button>
<modal-dialog info='modalShown' show='modalShown' width='400px' height='60%'>
<p>Modal Content Goes here</p>
</modal-dialog>
</div>
controller
app.controller('DataController', function ($scope,$http) {
$scope.showModal = false;
$scope.toggleModal = function () {
$scope.showModal = !$scope.showModal;
};
$http.get("/api/product").then(function (responses) {
$scope.ProductData = responses.data;
});
.......
........
});
app.directive('modalDialog', function () {
return {
restrict: 'E',
scope: {
show: '=info'
},
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
link: function (scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
scope.hideModal = function () {
scope.show = false;
};
},
template: "<div class='ng-modal' ng-show='show'><div class='ng-modal-overlay' ng-click='hideModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='hideModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
};
});
It looks like you're messing with your scope a little too much. If you check out http://codepen.io/dboots/pen/vLeXPj, I used the same $scope.showModal variable and the same the same $scope.toggleModal function to show/hide.
angular.module('testApp', [])
.controller('DataController', function($scope) {
$scope.showModal = false;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
})
.directive('modalDialog', function() {
return {
restrict: 'E',
replace: true, // Replace with the template below
transclude: true, // we want to insert custom content inside the directive
link: function(scope, element, attrs) {
scope.dialogStyle = {};
if (attrs.width)
scope.dialogStyle.width = attrs.width;
if (attrs.height)
scope.dialogStyle.height = attrs.height;
},
template: "<div class='ng-modal' ng-show='showModal'><div class='ng-modal-overlay' ng-click='toggleModal()'></div><div class='ng-modal-dialog' ng-style='dialogStyle'><div class='ng-modal-close' ng-click='toggleModal()'>X</div><div class='ng-modal-dialog-content' ng-transclude></div></div></div>"
};
});
Make a directive. Then include it in your controller.
See: https://docs.angularjs.org/guide/directive
I'm working on an AngularJS project that uses an API to deal with data. Now I'm implementing the 'create' functionality using $resource. Everything was going well except the naming conversion: I use camelCase but the API accepts snake_case only.
Is there a way to automatically convert these keys to snake_case?
Service:
services.factory('Salons', ['$resource',
function ($resource) {
return $resource('/salons/:slug', {
slug: "#slug"
});
}
]);
Controller:
controllers.controller('CreateSalonController', ['$scope', 'Salons',
function ($scope, Salons) {
$scope.submit = function() {
Salons.save(this.salon);
};
}
]);
View:
<form name="salonForm" role="form" ng-submit="submit()">
<div class="form-group">
<label for="salonContactFirstName">First name</label>
<input name="contactFirstName" type="text" class="form-control" id="salonContactFirstName" data-ng-model="salon.contactFirstName" />
</div>
...
I have not found any built-in solution so I implemented one:
A new service:
services.factory('Util', function () {
var Util = {
stringToSnakeCase: function (input) {
return input.replace(/([0-9A-Z])/g, function ($1) {
return "_" + $1.toLowerCase();
});
},
objectKeysToSnakeCase: function (input) {
var output = {};
_.each(input, function (val, key) {
output[Util.stringToSnakeCase(key)]
= _.isObject(val) ? Util.objectToSnakeCase(val) : val;
});
return output;
}
};
return Util;
}
);
And the updated controller:
controllers.controller('CreateSalonController', ['$scope', 'Salons', 'Util',
function ($scope, Salons, Util) {
$scope.submit = function() {
Salons.save(Util.objectKeysToSnakeCase(this.salon));
};
}
]);