2015-06-27 49 views
1

我想給valueng-repeatdirective獲取得到的值,但只有我被$index安慰的value控制檯爲undefiend無法從`directive`範圍

這裏有什麼問題?

我的代碼:

HTML:

<body ng-controller="main"> 
    <h1>{{index}}</h1> 

    <new-array index='$index' ng-repeat="value in values">{{value}}</new-array> 
    </body> 

JS:

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

myApp.controller('main', function ($scope) { 

    $scope.values = [{"name":"one", "num" : 1}, {"name":"two", "num" : 2}, {"name":"three", "num" : 3}] 

    $scope.index = 0; 

    $scope.update = function (num) { 
    $scope.index = num; 
    } 

}); 

myApp.directive("newArray", function() { 

    return { 

    scope : { 
     value : "=", 
     index : "=" 
    }, 

    link : function (scope, element, attrs) { 

     console.log(scope.value, scope.index) 
     //reusult as "undefined" 1 

    } 

    } 

}) 

Live Demo

回答

2

<new-array index='$index' ng-repeat="value in values">{{value}}</new-array> 

應該

<new-array index='$index' value='value' ng-repeat="value in values">{{value}}</new-array> 
0

在你的指令把示波器設置爲

scope : { 
     value : "=", 
     index : "=" 
    } 

這樣,您正在創建隔離範圍不從父繼承範圍。所以你必須將這個值作爲「simoco」解釋的值傳遞給指令。