【问题标题】:ng-repeat in a directive does not update if the data changes如果数据更改,指令中的 ng-repeat 不会更新
【发布时间】:2013-03-01 22:15:20
【问题描述】:

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

我有一个控制器,里面有一些数据。该数据被输入指令,并应使用本机 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/

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

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

    要将对象传递到您的隔离范围,请使用 '=':

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

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

    【讨论】:

    • 是的,就是这样。整个 @,=,& 事情让我感到困惑。谢谢人 :) 我会用新的小提琴更新我的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多