将AngularJS指令绑定到数组的映射 [英] Bind an AngularJS directive to a mapping of an array

查看:48
本文介绍了将AngularJS指令绑定到数组的映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受对象数组的指令.在标记中声明指令时,作用域具有一个对象数组,这些对象包装了指令所需的对象.因此,我需要在数组上应用map函数.正确的方法是什么,以便将对原始数组的更新反映在指令中?

I have a directive that takes an array of objects. When declaring the directive in markup, the scope has an array of objects that wrap the ones needed by the directive. So I need to apply a map function on the array. What's the right way to do this so updates made to the original array are reflected inside the directive?

这是一个幼稚的方法(我很惊讶地看到除了很多$ digest错误以外,大多数情况下它都是工作"):

Here's a Plunker with a naive approach (which I was surprised to see mostly "work" except for lots of $digest errors): http://plnkr.co/edit/GUCZ3c

推荐答案

您应该避免从Angular表达式中调用函数,除非该函数执行了一些非常轻量级的工作(例如快速计算).此问题对此有更多详细信息.

You should avoid calling a function from an Angular expression unless, among other things, that function does some very lightweight work (a quick computation, for instance). This question has more details on that matter.

在这种情况下,您应该缓存名称列表并将其绑定到指令.这是一个示例:

In your case, you should cache the name list and bind it to the directive. Here's an example:

app.controller('MainCtrl', function($scope) {  
    $scope.people = [
        { name: 'Alice'}, 
        { name: 'Bob' },
        { name: 'Chuck' }
    ];

    $scope.addName = function(name) {
        $scope.people.push({name: name});
    };

    $scope.$watch(function() { return $scope.people.length; }, function() {
        $scope.names = $scope.people.map(function(p) { return p.name; });
    });
});

您的指令代码保持不变.这是您的柱塞的叉子.

Your directive code remains the same. Here's a fork of your Plunker.

更新:我已经更改了代码,因此它使用了 $ watch 来自动更新名称列表,以遵循@KrisBraun的建议.

Update: I've changed the code so it uses a $watch to update the name list automatically, following @KrisBraun advice.

这篇关于将AngularJS指令绑定到数组的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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