简体   繁体   English

将对象传递给自定义指令而不创建观察者?

[英]Pass object to custom directive without creating watchers?

I have created a custom directive ("reusable component") which creates an isolated scope by binding to two objects passed to it via HTML-parameters.我创建了一个自定义指令(“可重用组件”),它通过绑定到通过 HTML 参数传递给它的两个对象来创建一个隔离的范围。 A problem with this quickly arises as I have up to 600 of these components in my document, which leads to 1200 watchers and poor performance.很快就会出现这个问题,因为我的文档中有多达 600 个这些组件,这导致 1200 个观察者和性能不佳。 I do not need these watchers, just some form of "bind once"-functionality when passing the objects.我不需要这些观察者,在传递对象时只需要某种形式的“绑定一次”功能。 Is there a way to accomplish this (or a workaround), or do I need to redesign my code?有没有办法完成这个(或解决方法),或者我需要重新设计我的代码吗?

(Passing data as one or several strings, instead of an object, is a much undesireable option.) (将数据作为一个或多个字符串而不是对象传递是一种非常不受欢迎的选择。)

You should use one-way binding:您应该使用单向绑定:

scope : {
    myField: '&'
    ....
}

and in directive using:并在指令中使用:

<my-directive my-field="::myDataObjectFromScope"></my-directive>

Maybe this will help也许会有所帮助

But if values are constantly at all, you should use service to separate your data from the business logic但是如果值始终不变,您应该使用服务将您的数据与业务逻辑分开

You can evaluate object manually without employing Angular directive scope bindings.您可以在不使用 Angular 指令范围绑定的情况下手动评估对象。 Say you have a directive some-component and you want to pass a config object in it preserving isolated directive scope.假设您有一个指令some-component并且您想在其中传递一个config对象,以保留独立的指令范围。 You could do something like this:你可以这样做:

<some-component config="controller.config"></some-component>

Then the directive could look like this:然后指令可能如下所示:

.directive('someComponent', function() {
  return {
    scope: {
      // some bindings, but not config
    },
    link: function(scope, element, attrs) {
      var config = scope.$parent.$eval(attrs.config)
      console.log(config)
    }
  }
})

$parent is necessary here because directive scope is isolated and you want to get an object defined in outer (parent) scope. $parent在这里是必要的,因为指令范围是隔离的,并且您希望获得在外部(父)范围中定义的对象。

Try it and see if it makes a difference for your set up.尝试一下,看看它是否对您的设置有影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM