How to use JavaScript inside {{}} AngularJS

无人久伴 提交于 2021-02-18 10:39:25

问题


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.


回答1:


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.




回答2:


You shouldn't be using templating like that - so Angular doesn't support it. Either create a function in the scope:

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

Or create a filter that does what you want to acheive:

angular.module('myModule').filter('myFilter', function () {

    return function (input) {
         if (!input) return input;

         return input.split('/').filter(function(n){return n}).reverse()[0];
    };
});

And use it like this:

<div>{{"a/b/c/d" | myFilter}}</div>



回答3:


{{}} tell Angular that in your view, you have an Expression to interpolate. Angular expressions do not support all of JavaScript. For documentation check here.

If you need all of JavaScript. It is better to wrap the logic in a controller function.

Excerpt from docs:

It might be tempting to think of Angular view expressions as JavaScript expressions, but that is not entirely correct, since Angular does not use a JavaScript eval() to evaluate expressions. You can think of Angular expressions as JavaScript expressions with following differences:

Attribute Evaluation: evaluation of all properties are against the scope doing the evaluation, unlike in JavaScript where the expressions are evaluated against the global window.

Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, where trying to evaluate undefined properties can generate ReferenceError or TypeError.

No Control Flow Statements: you cannot do any of the following in angular expression: conditionals, loops, or throw.



来源:https://stackoverflow.com/questions/20679322/how-to-use-javascript-inside-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!