如果数据发生更改,指令中的ng-repeat不会更新

时间:2013-03-01 22:15:21

标签: javascript angularjs angularjs-directive angularjs-scope

我在一个更大的项目上遇到了这个问题,我做了一个最简单的例子。

我有一个控制器,里面有一些数据。此数据将输入指令,并应使用本机ng-repeat显示。但是,当指令控制器运行时,它尚未解析角度变量,因此不会呈现重复。

如何使其工作以便重复使用需要预解析的外部变量?

这是一个小提琴。确保控制台打开,因为它显示该函数运行时未定义,但在1秒后定义:http://jsfiddle.net/paulocoelho/xqLAs/2/

这是我的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"}
    ];
}

这是我的dom

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

修改 我之前的代码中有一个错误,其中inputdata应该读取sl。

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

1 个答案:

答案 0 :(得分:2)

当您使用&#39; @&#39;时,结果始终为字符串。如果您将模板更改为显示{{x}}而不是{{x.val}},那么您将看到我的意思。

要将对象传递到隔离范围,请使用&#39; =&#39;:

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

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

另外,正如我(刚才)在other question中解释的那样,&#39; @&#39;如果使用,你需要使用$ attrs。$ observe或$ scope。$ watch()来异步获取值(这将是一个字符串)。使用&#39; =&#39;,您不必使用$ observe或$ watch。

相关问题