Building Your Own Directives
Directives can appear as HTML elements, attributes, comments, or CSS classes. Examples
<my-directive></my-directive>
<input my-directive>
<!– directive: my-directive–>
<input>
Defining a Directive
angular.module(‘app’, []).directive(‘myDir’, function() {
return myDirectiveDefinition;
});
Writing a Button Directive
escribe(‘button directive’, function () {
var $compile, $rootScope;
beforeEach(module(‘directives.button’));
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it(‘adds a “btn” class to the button element’, function() {
var element = $compile(‘<button></button>’)($rootScope);
expect(element.hasClass(‘btn’)).toBe(true);
});
});
});
Using the button directive
<button type=”submit”
>Click Me!</button>
Implementing a Custom Validation Directives
Implementing a custom validation directive
Now we have our tests in place, so we can implement the functionality of the directive:
myModule.directive(‘validateEquals’, function() {
return {
require: ‘ngModel’,
link: function(scope, elm, attrs, ngModelCtrl) {
function validateEqual(myValue) {
var valid= (myValue === scope.$eval(attrs.validateEquals));
ngModelCtrl.$setValidity(‘equal’, valid);
return valid ? myValue : undefined;
}
ngModelCtrl.$parsers.push(validateEqual);
ngModelCtrl.$formatters.push(validateEqual);
scope.$watch(attrs.validateEquals, function() {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue);
});
}
};
}); From: http://sitestree.com/?p=844
Categories:AngularJS, By Sayed Ahmed
Tags:
Post Data:2014-02-16 10:00:57
Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada