简体   繁体   English

angularjs指令在链接函数内使用参数

[英]angularjs directive use parameter inside link function

This is probably a stupid question, but I have been stuck on it for days and neither of the googled solutions panned out for me. 这可能是一个愚蠢的问题,但是我已经坚持了好几天,而谷歌解决方案都没有为我解决。

I'm writing an angular 1.4 app following a directive driven approach, so for any entity I have one or more widgets: 我正在按照指令驱动的方法编写一个angular 1.4应用程序,因此对于任何实体,我都有一个或多个小部件:

  • isolated scope 孤立范围
  • controller as 控制器为
  • bindToController true bindToController true

The problem is of the "user has stuff" variety. 问题在于“用户拥有东西”的多样性。

<user-widget>
   <stuff-widget userid="user._id"></stuff-widget>
</user-widget>

The userid passes nicely into the widget, but I would like to use it inside the stuff widget's link function, because stuff is really complicated and in the real world I need to grab various other parts as well. 用户ID很好地传递到了小部件中,但是我想在东西小部件的链接函数中使用它,因为东西确实很复杂,在现实世界中,我还需要抓住其他各个部分。

I tried various methods to get to the userid value (as suggested in various other stackoverflow discussions and elsewhere on the web) 我尝试了各种方法来获取用户ID值(如各种其他stackoverflow讨论和网络其他地方所建议的那样)

  • use bidrectional binding -> not effective 使用双向约束->无效
  • tried via scope and controller -> userid, uid not defined 通过作用域和控制器尝试过-> userid,未定义uid
  • require ^userWidget -> lost access to my controller 要求^ userWidget->无法访问我的控制器
  • use attrs.$observe('userid', ....) -> js error: userid not defined 使用attrs。$ observe('userid',....)-> js错误:未定义用户ID
  • passed it via pre link of the parent -> did work, but not a good idea/limited merits 通过父级的预链接传递了它->确实有用,但不是一个好主意/优点有限

I have a plunker with the various things I tried: http://plnkr.co/edit/SqlhYSteCDxMaAVZWCsy?p=info 我对尝试过的各种方法都一无所知: http ://plnkr.co/edit/SqlhYSteCDxMaAVZWCsy?p=info

The widgets look like this (working pre link variant) 小部件如下所示(工作前链接变体)

  function userWidget() {
    return {
      restrict: 'EA',
      scope:{},
      template: '<h2>User</h2> {{user.name}}<stuff-widget userid="user._id"></stuff-widget>',
      replace: false,
      controllerAs: 'userCtrl',
      bindToController: true,
      controller: 'UserCtrl',
      link: { // this actually works, not sure wether this a good idea
        pre: function preLink(scope, element, attrs, ctrl) {
          var uid = 1;
          scope.user = ctrl.findById(uid);
          scope.userid = scope.user._id;
    },
    post: function postLink(scope, element, attrs, ctrl) {}
      }

    };
  }

  function stuffWidget() {
    return {
      restrict: 'EA',
      scope: {
        uid: '=userid'
      }, 
      template: '<h3>User stuff</h3>stuffCtrl.userid inside widget: {{stuffCtrl.userid}}<div ng-repeat="stuff in stuffCtrl.userStuff">\
User id: {{stuff.userid}}: {{stuff.stuff}}\
</div>',
      replace: false,
      controller: 'StuffCtrl',
      controllerAs: 'stuffCtrl',
      bindToController: {
        userid: '='
      },
      link: function (scope, element, attrs, ctrl) {
    console.log('stuff ctrl userid:', ctrl.userid); // not defined
    console.log('stuff scope uid:', scope.uid); // not defined
    console.log('Scope parent userid: ',scope.$parent.userid); // undefined

    // didn't work either - userid not defined
    /* attrs.$observe('userid', function(value) {
      if (value) {
        ctrl.userid = userid;
        console.log('stuff ctrl userid observed:', ctrl.userid);
      }
    }); */
    ctrl.userStuff = ctrl.findByUserId(ctrl.userid);
      }
    };
  } 

I'm an angular beginner (first serious project) and so far my experience has been: "if it's hard to figure out, you are probably doing it the wrong way". 我是一个有经验的初学者(第一个认真的项目),到目前为止,我的经验是:“如果很难弄清楚,您可能做错了方法”。

So, 所以,

  • Did I miss an obvious way to access the param inside the link function? 我是否错过了在链接函数中访问参数的明显方法?
  • Did I screw up the ways I tried (especially $observe) because I incorrectly transferred them to my setting? 我是否因为不正确地将它们转移到我的设置而搞砸了尝试的方法(尤其是$ observe)?
  • Should I just stick the controller calls inside the template and be done with it? 我是否应该将控制器调用粘贴在模板中并完成模板?
  • Should I go about it in an entirely different way? 我应该以完全不同的方式去做吗? compile function? 编译功能? controller function? 控制器功能? whatever other angular depths I'm not yet familiar with? 我还不熟悉的其他角度深度?

After the link function has finished its execution you will have to wait one digest cycle to update the values in the isolated scope from the scope where the directive is used. 链接功能执行完后,您将必须等待一个摘要周期才能从使用指令的范围中更新隔离范围中的值。

You can try this snippet in stuffWidged : 您可以在stuffWidged中尝试以下代码段:

link: function(scope, element, attrs, ctrl) {
  var uid, usrStuff;

  scope.uid; // it is normal to be undefined here

  scope.$watch('uid', function(newUid) {
    uid = newUid;

    scope.uid; // is ready and is same as newUid

    usrStuff = ctrl.usrStuff = scope.usrStuff =
      ctrl.findById(uid);
  });
}
  1. Remove isolated scope from user-widget - do u really need it there? 从用户小工具中删除孤立的范围-您真的在那里需要它吗? If you are not defining any additional variables in directive scope - you do not actually need isolated scope. 如果您没有在指令范围内定义任何其他变量,则实际上不需要隔离范围。
  2. Isolated scope. 孤立的范围。 So user-widget should have some parameters? 因此,用户小部件应具有一些参数? Like: 喜欢:
 <user-widget widgetusers="model.users"></user-widget> 

then user-widget template will be: 然后,用户小部件模板将为:

 <stuff-widget ng-repeat="stuffuser in widgetusers" userid="stuffuser._id"></stuff-widget> 
  1. You can pass userId first to userWidget, then to stuffWidget: 您可以先将userId传递给userWidget,然后传递给stuffWidget:
 <user-widget userid="user._id"> <stuff-widget userid="userid"></stuff-widget> </user-widget> 

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

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