Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  54] [ 1]  / answers: 1 / hits: 39602  / 9 Years ago, wed, march 11, 2015, 12:00:00

I have a javascript library with a bunch of useful functions that I make use of across my website that does various things.



I know that I cannot access these functions from an ng-click, because the functions are outside of scope.



Is there a way to access them without having to declare a scope function that just makes a call to the function in the library?



Here is a jsfiddle with an example. I would like to know if there's a way to make the second link work.
This is simply because I do not like the idea of defining a function that will simply call another function. e.g.



HTML:



<div ng-click=doSomething()>Click Me (Working)</div>
<div ng-click=doSomethingElse()>Click Me (Not Working)</div>


Controller JS:



$scope.doSomething = function () {
doSomethingElse();
};


External Library JS:



function doSomethingElse() {
alert(SomethingElse);
}


<-------UPDATE------->



Thanks for the creative responses guys!
Vinay K's answer is the easiest and most obvious, but I decided to go with Ron E's answer.
The reason is that I already have a global module with a collection of reusable directives and that would make it easier and cleaner to implement in my HTML. Also because I sometimes use more than one function from the library and then would have to chain them in the onclick:



onlick=func1(); func2(); func3();


Where a directive is just cleaner and I can call as many functions as I like while doing other stuff as well.


More From » angularjs

 Answers
29

You could use a directive, here is an example:



// in your JS source
angular.directive('something', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
alert('yup');
});
}
};
}]);

// in your HTML file
<button type=button something>Click Me!</button>


This allows you to reuse your various code chunks / functions across your entire project pretty easily.


[#67473] Tuesday, March 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;