Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JavaScript inside {{}} AngularJS

I know that {{}} can interpret a expression but when I try to use javascript in it, it does not work like {{"a/b/c/d/".split('/').filter(function(n){return n}).reverse()[0]}}

I need to use this to get slug value from url.

Please suggest how to achieve this with angularjs, the source of the url is from external feed, hence I have very limited control on this.

like image 863
whizcreed Avatar asked Dec 19 '13 10:12

whizcreed


People also ask

Can I use JavaScript in AngularJS?

You need to execute a separate java-script function. For an angular application it is not a proper way to run javascript out of scope of angular. It will ensure that the external function exist before starting app. It will add more flexibility and control over the java script function in angular.

Can we use plain JavaScript in Angular?

In a plain JavaScript project, you can include the library in the script tag of your index. html and then the library is available to use. But in an Angular project, following the same steps might not actually work. In fact, the compiler may throw an error at the usage of the library.

Can you write JavaScript in HTML Angular?

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.


1 Answers

Full JS is not supported, and even it were, it would be a bad practice.

I recommend you to put this at least on a scope function in your controller.
Even better would be to put it in a service or in a filter, so if you want to reuse it later for other purposes you can:

$scope.getSlug = function( str ) {
  return str.split( "/" ).filter(function( n ) {
    return n;
  }).reverse()[ 0 ];
};

And then, in your template:

{{ getSlug( "a/b/c/d/" ) }}
{{ getSlug( myModelProperty ) }}

Also, it's valid to read the Angular docs about expressions.

like image 158
gustavohenke Avatar answered Oct 16 '22 18:10

gustavohenke