Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call javascript function outside of scope on ng-click

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.

like image 808
WJK Avatar asked Mar 11 '15 19:03

WJK


1 Answers

ng-click expression (or any other expression in angular) will be evaluated in the context of the scope.

As doSomethingElse is not defined on scope it will not work.

Use onclick instead of ng-click

<div ng-click="doSomething()">Click Me</div>
<div onclick="doSomethingElse()">Click Me </div>
like image 69
Vinay K Avatar answered Sep 18 '22 17:09

Vinay K