AngularJS:传递$ index作为$ emit break函数的参数

时间:2014-01-17 00:25:02

标签: angularjs javascript-events indexing parameter-passing angularjs-ng-repeat

我有一个论坛主题(主题)列表,当用户将鼠标悬停在每个主题上时,我希望它的元数据显示在一个单独的面板中,以确定选择了哪个主题我试图将$ index作为参数传递$ emit但这似乎打破了这个功能。

查看:

<header ng-include="includes.header.src"></header>
<div id="content-wrapper">
    <div ng-include="includes.threadList.src" id="content-left"></div>
    <div id="content-divider"></div>
    <div ng-include="includes.threadDetails.src" id="content-right"></div>
</div>

threadList include(发生问题的地方):

<ul id="threadList">
    <li ng-repeat="thread in threadList | filter:includes.header.searchQuery" ng-mouseover="$emit('updateThreadDetails', {{$index}})">  
        <a href="/#/threads" ng-click="">
        {{thread.title}}, moused over {{count}} times. This is item {{$index}}
        </a>
    </li>
</ul>

threadDetails包括:

<h3>{{includes.threadDetails.title}}</h3>

控制器:

function threadListCtrl($scope){
    $scope.count = 0;
    $scope.$on('updateThreadDetails', function(event,index) {
        $scope.count++;
        $scope.includes.threadDetails.title = index;    //$scope.threadList[index].title;
    });

    $scope.threadList = [
        {title: 'I like horse'},
        {title: 'I like turtle'},
        {title: 'I like actor'}
    ];
}

通过ng-mouseover="$emit('updateThreadDetails', 'myString')"传递刺痛按预期工作(includes.threadDetails.title变为'myString')。这是来自threadList的健康示例文本:

I like horse, moused over 26 times. This is item 0
I like turtle, moused over 26 times. This is item 1
I like actor, moused over 26 times. This is item 2

当传递{{$ index}}时,输出生病,'moused over x times' x始终为0且线程详细信息保持不变。作为一种解决方法,我尝试预先设置{{$ index}},所以我只是传递一个原语,虽然这不起作用:

ng-mouseover="index = '{{$index}}'; $emit('updateThreadDetails', index)"

1 个答案:

答案 0 :(得分:2)

您传递给ngMouseOver的表达式中不需要数据绑定(来自双花括号),因为Angular已经希望将其作为Angular表达式处理(使用$interpolate)。因此,您可以直接使用变量$index,如下所示:

ng-mouseover="$emit('updateThreadDetails', $index)"

此外,我假设您还想单独更新每个项目的计数。所以也许你更喜欢:

$scope.count[index]++;

在你的html中显示它:

moused over {{count[$index]}}

demo fiddle