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

查看:75
本文介绍了使用$ 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.

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

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.

推荐答案

在伪指令中,作用域绑定发生在链接的较晚阶段,并且控制器执行得很早,因此如果要获取在属性中提供的值,在您的指令控制器中的指令中,您需要在控制器中使用$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天全站免登陆