Angular JS并将复杂对象数组作为属性传递给指令

时间:2014-12-29 20:41:29

标签: javascript angularjs

我无法通过属性将此复杂对象数组传递给指令。我做错了什么,为什么不对?

jsfiddle

剪切并粘贴代码

<div ng-controller="MyCtrl">
    <pass-object obj="obj"></pass-object>
</div>

var myApp = angular.module('myApp',[]);

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=' },
        template: '<div ng-repeat="foo in foos">Hello, {{foo.prop}}!</div></div>'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.obj = [{ prop: "hello" }, {prop: "world"}];
});

2 个答案:

答案 0 :(得分:5)

您正在指令模板中迭代foos。你没有通过foos,你通过了obj。试试这个:

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=' },
        template: '<div ng-repeat="o in obj">Hello, {{o.prop}}!</div></div>'
    };
});

Updated fiddle.

答案 1 :(得分:3)

根据您的范围定义foos,没有名为obj的范围属性,它应为scope: { obj: '=' }

template: '<div ng-repeat="foo in obj">Hello, {{foo.prop}}!</div></div>'

或者您可以将范围配置更改为:

scope: { foos: '=obj' },