Bojan Tomić Bojan Tomić - 1 month ago 7
AngularJS Question

Transform Angular Directive in Vanila JavaScript function

My problem is how to transfer my Angular Directive to an JavaScript function. Ben searching for a weak now with out any success.

Since I have confidentiality agreement with my employer I can't share any of my code, but I think that question is easily understood.

Can any one give me some advice?

Here is a simple example, Ill try to be clear as a beginner can be.

This is a directive:

app.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: true,
template: '<p style="background-color:{{color}}">Hello World',
link: function(scope, elem, attrs) {
elem.bind('click', function() {
elem.css('background-color', 'white');
scope.$apply(function() {
scope.color = "white";
});
});
elem.bind('mouseover', function() {
elem.css('cursor', 'pointer');
});
}
};
});


What I would like to do is something like this:

function directiveWraper(scope, elem, attrs){
app.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: true,
template: '<p style="background-color:{{color}}">Hello World',
link: function(scope, elem, attrs) {
elem.bind('click', function() {
elem.css('background-color', 'white');
scope.$apply(function() {
scope.color = "white";
});
});
elem.bind('mouseover', function() {
elem.css('cursor', 'pointer');
});
}
};
});
}


So I would like to wrap a directive in a javascript function, an pull all the params in that function.

Answer

So for me it looks like you are looking for is a function that takes a DOM element and applies changes to id (DOM manipulation, style or something else). What an angular directive does, is nothing but wrap changes to the dom into a container.

If you don't want to use angular.js for you code i guess best fitting would be jQuery for what you want to achieve. Actually what the directive is using is a lightweight version of jQuery.

What should do the trick for you is take everything out of the link function and replace elem with a jQuery object like this:

var $elem = $(".myclass");
$elem.bind('click', function() {
    $elem.css('background-color', 'white');
    //do something else onclick
});

$elem.bind('mouseover', function() {
    $elem.css('cursor', 'pointer');
});

You might need to do some more changes but this should lead you to the right track. And in addition you might want to call this code after the document loaded, to ensure that the element you are looking for is on the DOM.

$.ready(function(){
     //..do stuff in here after the document.ready event fired
});