简体   繁体   中英

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; so I pass the users to the directive, and create a reference to the setUser() function.

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

This is the relevant code for 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. 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:

<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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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