【发布时间】:2015-10-13 00:10:26
【问题描述】:
我想将一些数据从控制器传递到指令,所以先指令:
.directive('myDirective', function() {
'use strict';
return {
restrict: 'EA',
// templateUrl here
controller: DataController,
link: function(scope, elem, attrs, ctrl) {
var data = ctrl.data,
config = {
data: data,
xkey: 'y',
ykeys: ['a', 'b'],
// ... more code here
};
//.. more irrelevant code
}
};
当我这样放置数据时,效果很好:
nslive.controller('DataController', ['Data', 'socketio', '$routeParams', DataController]);
function DataController(Data, socketio, $routeParams) {
'use strict';
var vm = this;
vm.data = [
{y: '2014', a: 12500, b: 38000}, {y: '2015', a: 10500, b: 27000},
{y: '2016', a: 38640, b: 13545}, {y: '2017', a: 38640, b: 13000}
];
// more code here
}
但是,当我像这样将它放在 '.success()' 回调函数中时,指令无法看到数据:
nslive.controller('DataController', ['Data', 'socketio', '$routeParams', DataController]);
function DataController(Data, socketio, $routeParams) {
'use strict';
var vm = this;
vm.urlJobname = $routeParams.jobname;
Data
.all(vm.urlJobname)
.success(function(data) {
console.log('I got here!'); // this is shown successfully in the chrome console
vm.data = [
{y: '2014', a: 12500, b: 38000}, {y: '2015', a: 10500, b: 27000},
{y: '2016', a: 38640, b: 13545}, {y: '2017', a: 38640, b: 13000}
];
});
}
我觉得和变量作用域有关,但是不知道怎么设置这样的全局变量,请指教。谢谢。
【问题讨论】:
-
您可以将
$scope传递给指令。或在指令中使用scope: {<some variables>}并在任何controller中填充特定变量
标签: angularjs variables controller scope directive