how to access object property via isolate scope without two-way binding?

只愿长相守 提交于 2019-12-25 06:25:13

问题


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

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

I prefer not to use curly braces:

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

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

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

If I use:

scope {
  productId: '@'
}

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

If I use:

scope {
  productId: '&'
}

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

If I use:

scope {
  productId: '='
}

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?


回答1:


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

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

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.

Here's an example:

 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);
        }         
    };
});

demo fiddle




回答2:


I'm afraid there is no binding that fits your need, you can try this:

link:function(scope, element, attr){
          scope.productId = scope.$parent.$eval(attr.productid);
}

But this approach is not recommended

DEMO

The recommended approach is using @ binding and {{}} in your html

  scope:{
    productId: '@'
  }

Your HTML:

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

DEMO



来源:https://stackoverflow.com/questions/21057320/how-to-access-object-property-via-isolate-scope-without-two-way-binding

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