I have a large web form that I have built, (over 100 fields) and I want to add AngularJS to enable users to type into the form and run Javascript to store the Angular Model in a database as they type. Clearly I don't want to send data to the database every time the user alters a tiny piece of data, so I want to use the ng-model-options
directive to tell Angular to only fire off an updateOn
after 500ms or so.
I really don't want to apply a huge amount of angular to every <input>
tag in my HTML though, that's a lot of typing, and if I ever want to change something, it's a lot of places to go through and manually update. What I'd really like to do is something like $("input").setDirective()
or somesuch thing if it existed. I realize I'm thinking about this in a jQuery-type way, so I'm interested to hear the "proper" Angular way of applying the same set of directives to every element in my DOM that matches some selector.
Thanks!
It is tempting to do too much work in the AngularJS controller. After all, the controller is where the view first has access to JavaScript via $scope functions. However, doing this will cause you to miss out on code sharing across the site and is not recommended by AngularJS documentation.
The $ in AngularJs is a built-in object.It contains application data and methods.
Overview. Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. The compilation is a process of walking the DOM tree and matching DOM elements to directives. Note: This document is an in-depth reference of all directive options.
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Little modification to @Bodzio answer
HTML
<div ng-app="app">
<input type="text" name="something" />
<input type="text" />
<input type="text" />
<input type="text" name="different" />
<input type="radio" name="different" />
</div>
JS
var app = angular.module('app', []);
app.directive('input', function() {
return {
restrict: 'E',
link: function (scope, element, attributes) {
// filter the element using attributes
if (attributes.type === "text" && attributes.name) {
element[0].value = "It works!";
}
}
};
});
JSFIDDLE DEMO
You can just create a directive for <input>
tag like this:
var app = angular.module('app', []);
app.directive('input', function() {
return {
restrict: 'E',
link: function (scope, element) {
element[0].style.backgroundColor = "red";
}
};
});
demo: http://jsfiddle.net/zjdscakc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With