使用 $attrs 评估带有花括号的属性 [英] Using $attrs to evaluate attribute with curly braces in it

查看:21
本文介绍了使用 $attrs 评估带有花括号的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个使用以下标记的文件上传指令.

I am creating a file upload directive which uses the following markup.

<file-upload
    name="myUploader"
    upload-url="{{$root.apiSettings.apiUrl}}/files"  
    auto-upload="true"
></file-upload>

我正在尝试像这样在指令控制器中获取 upload-url 属性.

I am trying to get the upload-url attribute in the directive controller like this.

$scope.uploadUrl = $attrs.uploadUrl

显然这不起作用,因为我只是得到带有花括号的未评估表达式.我尝试使用 $scope.$eval 对其进行评估,但出现解析错误,提示 { 在第 2 列是无效字符.

Obviously this doesn't work as I just get the un-evaluated expression with the curly braces in it. I tried using $scope.$eval to evaluate it but I got a parse error saying { was an invalid character at column 2.

接下来我尝试使用 ng-attr-upload-url 和不使用 $eval .

Next i tried using ng-attr-upload-url with and without using $eval on it.

我通常试图避免使用隔离范围绑定,这可能会奏效,因为我的指令中的大多数属性都是简单的一次,一种方式绑定,我想减少手表的数量,所以如果这可以使用不起眼的 $attrs 集合来实现,我很想知道如何.

I'm generally trying to avoid using isolate scope bindings which would probably do the trick because most of the attributes in my directives are simple one time, one way bindings and I want to cut down on the number of watches so if this can be achieved using the humble $attrs collection I'd love to know how.

推荐答案

In 指令作用域绑定发生在链接的后期阶段,并且控制器很早就执行,因此如果您想获取在指令的控制器中的指令,您需要在控制器中使用 $interpolate ,考虑到您没有使用隔离范围.

In directives scope binding happens at a very later stage in the link and the controller gets executed very early so if you want to get the values provided in attributes of the directive in your directive's controller you need to use $interpolate in your controller , considering you are not using isolated scope.

要在控制器中获得正确的值,您可以使用 $parse$interpolate ,具体取决于您通过指令的属性传递的内容.如果您只传递属性的名称,那么您可以使用 $parse 否则,如果您有一个内插字符串,您需要使用 $interpolate 在给定的上下文中执行.

To get the proper value in the controller you can use either $parse or $interpolate depending upon what you have passed through your directive's attributes. If you passed just the name of the property then you can use $parse otherwise if you have an interpolated string you need to use $interpolate which gets executed in the given context.

在你的情况下,你需要像下面这样使用 $interpolate

In your case you need to use $interpolate like below

在 HTML 中

  <body ng-app='app' ng-controller='mCTRL'>
    <h1>Hello Plunker!</h1>
    <file-upload
    name="myUploader"
    upload-url="{{url}}/files"  
    auto-upload="true"
     ></file-upload>
  </body>

您的指令应如下所示

app.directive('fileUpload',function(){

  return{
    restrict:'EA',
    controller:function($scope,$attrs,$interpolate){
     var myUrl=$interpolate($attrs.uploadUrl)($scope)
    },
    link(scope,elem,attrs,ctrl){

    }

  }

})

这篇关于使用 $attrs 评估带有花括号的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆