Answer the question
In order to leave comments, you need to log in
How to create a "standalone" AngularJS directive?
I started playing AngularJS not so long ago and I'm just going to create something real on it.
Today, a Toaster question about directives pointed to a gap that I was never able to close.
You can explain for a long time what exactly I'm asking about, and therefore I'll show it better -
<ng-custom-input remove-char="s"></ng-custom-input>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>angular</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
</head>
<body ng-app="app">
<script>
var app = angular.module('app', []);
app.controller('InputRemoveCharController', ['$scope', function($scope){
this.model = {
value: ''
};
}]);
app.directive('inputDirective', ['$injector', function(){
return {
require: '?ngModel' ,
link: function($scope, iElm, iAttrs, model) {
if(!model){
return;
}
var charForRemove = iAttrs.char;
model.$setViewValue = function(value){
if(value.indexOf(charForRemove) > -1){
value = value.replace('s', '');
model.$setViewValue(value);
model.$render();
}
};
}
};
}]);
</script>
<div ng-controller="InputRemoveCharController as inputRemoveCharController">
<input type="text" input-directive char="s" ng-model="inputRemoveCharController.model.value">
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>angular</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
</head>
<body ng-app="app">
<script>
var app = angular.module('app', []);
app.controller('InputRemoveCharController', ['$scope', function($scope){
this.model = {
value: ''
};
}]);
app.directive('inputDirective', ['$injector', function(){
return {
require: '?ngModel' ,
link: function($scope, iElm, iAttrs, model) {
if(!model){
return;
}
var charForRemove = iAttrs.char;
model.$parsers.push(removeChar);
function removeChar(string){
if(string.indexOf(charForRemove) > -1){
string = string.replace(charForRemove, '');
model.$setViewValue(string);
model.$render();
}
}
}
};
}]);
</script>
<div ng-controller="InputRemoveCharController as inputRemoveCharController">
<input type="text" input-directive char="s" ng-model="inputRemoveCharController.model.value">
</div>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
where is the model and controller
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question