AngularJS Directive element method binding - TypeError: Cannot use 'in' operator to search for 'functionName' in 1

CodeVirtuoso picture CodeVirtuoso · May 14, 2015 · Viewed 34.2k times · Source

This is the controller of the main template:

app.controller('OverviewCtrl', ['$scope', '$location', '$routeParams', 'websiteService', 'helperService', function($scope, $location, $routeParams, websiteService, helperService) {
    ...     
    $scope.editWebsite = function(id) {
        $location.path('/websites/edit/' + id);
    };
}]);

This is the directive:

app.directive('wdaWebsitesOverview', function() {
    return {
        restrict: 'E',
        scope: {
            heading: '=',
            websites: '=',
            editWebsite: '&'
        },
        templateUrl: 'views/websites-overview.html'
    }
});

This is how the directive is applied in main template:

<wda-websites-overview heading="'All websites'" websites="websites" edit-website="editWebsite(id)"></wda-websites-overview>

and this is method is called from directive template (website-overview.html):

<td data-ng-click="editWebsite(website.id)">EDIT</td>

QUESTION: When EDIT is clicked, this error appears in the console:

TypeError: Cannot use 'in' operator to search for 'editWebsite' in 1

Does anyone know what goes on here?

Answer

floribon picture floribon · May 14, 2015

Since you defined an expression binding (&), you need to explicitly call it with an object literal parameter containing id if you want to bind it in the HTML as edit-website="editWebsite(id)".

Indeed, Angular needs to understand what this id is in your HTML, and since it is not part of your scope, you need to add what are called "locals" to your call by doing:

data-ng-click="editWebsite({id: website.id})"

Or as an alternative:

data-ng-click="onClick(website.id)"

With the controller/link code:

$scope.onClick = function(id) {
  // Ad "id" to the locals of "editWebsite" 
  $scope.editWebsite({id: id});
}

AngularJS includes an explanation of this in its documentation; look for the example involving "close({message: 'closing for now'})" at the following URL:

https://docs.angularjs.org/guide/directive