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

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

问题描述

我想将产品的 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 的代码片段,通常放在在诸如 {{ 表达式 }} 之类的绑定中.表达式由$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天全站免登陆