AngularJS 指令元素方法绑定 - TypeError:无法使用“in"运算符在 1 中搜索“functionName" [英] AngularJS Directive element method binding - TypeError: Cannot use 'in' operator to search for 'functionName' in 1

查看:28
本文介绍了AngularJS 指令元素方法绑定 - TypeError:无法使用“in"运算符在 1 中搜索“functionName"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是主模板的控制器:

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

这是指令:

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>

这是从指令模板(website-overview.html)调用的方法:

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: 无法使用in"运算符在 1 中搜索editWebsite"

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

有人知道这里发生了什么吗?

Does anyone know what goes on here?

推荐答案

由于您定义了表达式绑定 (&),因此您需要使用包含 的对象字面量参数显式调用它id 如果你想在 HTML 中将它绑定为 edit-website="editWebsite(id)".

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)".

确实,Angular 需要了解这个 id 在您的 HTML 中是什么,并且由于它不属于您的范围,您需要添加所谓的locals";通过执行以下操作来接听您的电话:

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})"

或者作为替代:

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 在其文档中包含对此的解释;在以下 URL 中查找涉及 "close({message: 'closed for now'})" 的示例:

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

这篇关于AngularJS 指令元素方法绑定 - TypeError:无法使用“in"运算符在 1 中搜索“functionName"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆