如何在没有双向绑定的情况下通过隔离作用域访问对象属性? [英] how to access object property via isolate scope without two-way binding?

查看:81
本文介绍了如何在没有双向绑定的情况下通过隔离作用域访问对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将产品的ID传递给这样的指令:

I want to pass a product's id to a directive like so:

<widget product-id="product.id"></widget>

我不想使用花括号:

<widget product-id="{{product.id}}"></widget>

因为它比较冗长,所以我想匹配ng-model用法的样式.

because it's more verbose, and I want to match the style of ng-model usage.

我想使用隔离范围,以免意外修改小部件内的product.id.

I want to use isolate scope so that I can't accidentally modify product.id inside the widget.

如果我使用:

scope {
  productId: '@'
}

然后在我的指令模板中:{{productId}}给我字符串"product.id"

Then in my directive template: {{productId}} gives me the string "product.id"

如果我使用:

scope {
  productId: '&'
}

我在指令模板{{productId}}中看不到任何输出,据我了解,&是用于绑定函数而非属性的.

I see no output in my directive template {{productId}}, and as I understand it & is for binding functions not properties.

如果我使用:

scope {
  productId: '='
}

我得到了想要的确切值(一个数字),但是这种双向绑定不容易受到影响并且不容易在小部件中更改product.id吗?

I get the exact value that I want (a number), but isn't this two-way binding and vulnerable to changing the product.id in the widget?

推荐答案

如果要避免两次卷曲,可以使用 $parse 自己处理角表达式:

If you want to avoid the double curlys you can use $parse to process the Angular expression yourself:

表达式是类似JavaScript的代码段,通常放置在 在诸如{{expression}}之类的绑定中.表达式由 $ parse服务.

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by the $parse service.

要在指令中使用$parse,您需要提供要分析的范围(上下文).由于您使用的是隔离范围,因此product.id的值将在指令的父级范围内-因此我们将使用scope.$parent.

To use $parse in your directive you need to provide a scope (context) to parse against. Since you're using an isolated scope the value of product.id will be on the directive's parent's scope- so we'll use scope.$parent.

这是一个例子:

 myApp.directive('widget', function ($parse) {
    return {
        restrict: "E",
        scope: {
            productId: '@'
        },
        link: function(scope, element, attr) {          
               nvalue = $parse(scope.productId)(scope.$parent);
               console.log("parse result",nvalue);
        }         
    };
});

演示小提琴

这篇关于如何在没有双向绑定的情况下通过隔离作用域访问对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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