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.
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.
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.
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With