简体   繁体   中英

AngularJS directive: '&' in isolated scope isn't working as expected

I'm trying to pass on a method from the controller into my directive. This is how I'm doing it:

In the controller:

$scope.getEmployees = function()
{
    return {2: 'Jane', 3: 'Bob', 4: 'Smith'};
}

$scope.getSelected = function()
{
    return 3;
}

In the view/HTML:

<mydirective data-placeHolder="Choose an employee.." 
       data-getOpts="getEmployees()" data-getSelected="getSelected()" />

In the directive:

var dir = 
{
   restrict: 'E',
   templateUrl : 'views/mydirective.html',
   scope: {
       placeholder: '@',
       getSelected: '&',
       getOpts: '&'
   },   
   controller: ['$scope', '$element', '$attrs', 
       function($scope, $element, $attrs)
       {
           console.log( $scope.getOpts() );
       }],

};

MyApp.directive('mydirective', function()
 {
     return dir;
 });

However, the following line in the directive's controller:

   console.log( $scope.getOpts() );

Produces undefined rather than returning the object or the function set in the controller's getEmployees() function.

What am I doing wrong?

It is relating to naming convention. You need to convert the camel case to dash separated words like this

data-get-opts="getEmployees()" 

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