简体   繁体   English

Angular自定义指令-传递对父函数的引用

[英]Angular custom directive - pass reference to parent function

I'm refactoring some code into a custom directive which takes a list of users from the parent scope and presents them in tabular format. 我将一些代码重构为一个自定义指令,该指令从父级作用域获取用户列表,并以表格格式显示它们。 The application user can select one of the users in the table to view details. 应用程序用户可以选择表中的用户之一来查看详细信息。 The users and the setUser() function are in the parent controller, not the directive controller; userssetUser()函数位于父控制器中,而不是指令控制器中。 so I pass the users to the directive, and create a reference to the setUser() function. 所以我将用户传递给指令,并创建对setUser()函数的引用。

app.directive('myDirective', function() {
   return {
        restrict : 'E',
        templateUrl : 'app/view.html',
        controller : 'ViewController',
        scope: {
            setUser: '&',
            users: '='
        }
   }
});

This is the relevant code for view.html : 这是view.html的相关代码:

<div ng-repeat="user in users">
    <div ng-click="setUser(user)">...</div>
</div>

This is how I use the directive: 这就是我使用指令的方式:

<my-directive users="users" set-user='setUser()'></my-directive>

The problem is that when I click the user in the table, and the setUser function is called, the user passed to the function is always undefined. 问题是,当我单击表中的用户并调用setUser函数时,传递给该函数的用户始终是未定义的。 I'm not sure how to get around this. 我不确定该如何解决。

Use a different function in your directive: 在指令中使用其他函数:

<div ng-repeat="user in users">
  <div ng-click="doSetUser(user)">...</div>
</div>

And in the directive link/controller: 并在指令链接/控制器中:

$scope.doSetUser = function(user) {
  // Call the function bound to the directive with extended scope
  $scope.setUser( {user: user} );
}

This way, the function you pass to the directive will have access to the user variable right in the HTML (technically, its scope is extended with the local user variable), hence you can do: 这样,您传递给指令的函数将有权访问HTML中的user变量(从技术上讲,它的范围已由本地user变量扩展),因此您可以执行以下操作:

<my-directive users="users" set-user='setUser(user)'></my-directive>

I make some changes, you can try it: 我进行了一些更改,您可以尝试:

 app.directive('myDirective', function() { return { restrict : 'E', templateUrl : 'app/view.html', controller : 'ViewController', scope: { setUser: '=', //Changed '&' -> '=' users: '=' } } }); 

and

 <my-directive users="users" set-user="setUser"></my-directive> //Change setUser() -> setUser 

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

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