2017-09-25 56 views
0

我正在製作實時d3可視化圖表,但無法將控制器範圍存入指令。AngularJs:如何將contorller範圍變量存入指令

var app = angular.module('myChart', ['ngMaterial', 'ngMessages']); 

app.controller('chartCtrl', function($scope, $http, $mdDialog, $window){ 

// Get chart setting 
$http.get('chart_setting.php').then(function(res){ 
    $scope.info = res.data; 
    $scope.me = 'hello'; 
}); 

}); 

app.directive('motionChart', function(){ 
return { 
    restrict: 'E', 
    link: link, 
    scope: {info: "="} 
} 

function link(scope, el, attr){ 
    console.log(scope.info);// Here is info data in json 
    console.log(scope.me);// Try to fetch simple string but not success 
} 

}); 

在指令中,我需要「info」和「me」範圍變量。但無法訪問。

如果我安慰範圍則數據llook像

print whole scope

範圍打印成功,但是當我得到scope.anyVariable我得到取消定義。

感謝

+0

這是一段時間,因爲我做了AngularJS,但我猜你可能需要範圍:{信息:「=」,我說:「=」}中的指令。 –

+0

試過但沒有成功......它在模板中工作良好,但沒有鏈接:( –

回答

0
<motion-chart info="info"></motion-chart> 

app.directive('motionChart', function(){ 
return { 
    restrict: 'E', 
    link: link, 
    scope: {info: "="} 
} 

function link(scope, el, attr){ 
    var dataWatch = scope.$watch("info", function(n,o){ 
     if(n) init(); 
    }); 

    scope.$on("$destroy", function(){ 
     dataWatch(); //stops watching 
    }); 

    function init(){ 
     console.log(scope.info); //gives value of info 
     console.log(scope.$parent.me); //gives controller $scope.me value 
    } 
} 

});