0

I have this problem on a larger project and I made the most simplistic example.

I have a controller that has some data in it. This data is fed into the directive and should be displayed using the native ng-repeat. However, when the directive-controller runs, it has not yet parsed the angular variable, thus not rendering the repeat.

How do I make it work so that the repeat works with that outside variable that needs pre-parsing?

Here is a fiddle. Make sure you have the console open as it shows there that it is undefined when the function runs, but defined 1 second later: http://jsfiddle.net/paulocoelho/xqLAs/2/

Here my JS:

var module = angular.module('testApp', [])
    .directive('test', function () {
    return {
        restrict: 'E',
        template: '<p ng-repeat="x in sl">{{x.val}}</p>', // this wont work :(
        scope: {
            sl: '@sl'
        },
        link: function ($scope, $element, $attrs) {
            console.log($attrs.sl);        // this will return undefined
            setTimeout(function(){ 
                console.log($attrs.sl);    // this will return the correct list
            },1000);
        }
    };
});

function sweetCtrl($scope){
    $scope.someList = 
    [
        {"val":"a"},
        {"val":"b"},
        {"val":"c"},
        {"val":"d"},
        {"val":"e"},
        {"val":"f"}
    ];
}

Here is my dom

<div ng-app="testApp" ng-controller="sweetCtrl">
    <p>raw list: {{someList}}</p>
    <p>repeat list:</p>
    <test sl="{{someList}}"></test>
</div>

EDIT: There is was an error on my previous code where inputdata should read sl.

解决方案的小提琴在这里:http: //jsfiddle.net/paulocoelho/xqLAs/3/

4

1 回答 1

2

当您使用“@”时,结果始终是一个字符串。如果您将模板更改为显示 {{x}} 而不是 {{x.val}} 您会明白我的意思。

要将对象传递给您的隔离范围,请使用“=”:

<test sl="someList"></test>

template: '<p ng-repeat="x in sl">{{x.val}}</p>', // this will work :)
scope: {
     sl: '='
},

另外,正如我(刚才)在你的另一个问题中解释的那样,当使用 '@' 时,你需要使用 $attrs.$observe 或 $scope.$watch() 来异步获取值(这将是一个字符串) . 使用'=',您不必使用$observe 或$watch。

于 2013-03-01T22:26:15.113 回答