angularJS - 指令无法获取数组值的`index`

时间:2017-05-15 05:41:27

标签: angularjs angular-directive

我将数组传递给directive并在指令方法中获取它。但我想获得index的价值。但得到undefiend。这是什么问题?

阵列创建:

var dataSize = gridView.baseData.length / viewPorts;
        for( var i = 0; i < dataSize; i++ ){
            gridView.pages[i] = {
                show : i ==0 ? true:false,
                pageData : gridView.baseData.splice( 0, viewPorts )
            };
        }
        return gridView.pages;

这是我的指示:

var dataGridMaker = function( ) {

    return {
        scope: {
            "pages" : "="
        },
        replace: true,
        template : GridTemplate.join(''),
        link: function(  scope, element, attrs ) {
            console.log( scope.pages ); //getting all array values
            console.log( scope.pages[0] ); //undefined-why?
        }
    }

}

这是控制台:

[]0: Object 1: Object 2: Object 3: Object 4: Object 5: Object 6: Object 7: Object 8: Object 9: Objectlength: 10__proto__: Array(0)
dataGridDirective.js:24 undefined

1 个答案:

答案 0 :(得分:1)

这可能是未解决的承诺或范围更改(取决于您在控制器中执行的操作)。尝试将console.log( scope.pages[0] );包裹在超时中,没有延迟,看看会发生什么。像这样:

$timeout(function () {
   console.log( scope.pages[0] );
});