我有一个查询服务的 Controller ,如下所示:
app.controller('CandListCtrl', ['$scope', 'Cand',
function ($scope, Cand) {
Cand.query(function(data) {
//data processing can happen here
$scope.candidates = data;
});
}]);
我的服务查询 Google 表格:
var sheetServices = angular.module('candServices', []);
sheetServices.factory('Cand', ['$rootScope',
function($rootScope){
return {
query: function(callback) {
Tabletop.init({
key: '{{my key}}',
simpleSheet: true,
parseNumbers: true,
callback: function(data, tabletop) {
if(callback && typeof(callback) === "function") {
$rootScope.$apply(function() {
callback(data);
});
}
}
});
}
};
}]);
我的指令:
app.directive('timeline', function () {
return function (scope, element, attrs) {
var events = scope.candidates;
console.log(events); //undefined
}
})
我在路线部分 View 中使用时间线指令:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/cand-list.html',
controller: 'CandListCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
cand-list.html:
<div id="timeLine"><div timeline ng-style="myStyle"></div></div>
我的问题是我无法从指令中访问 $scope.candidates,因为它的范围仅限于查询函数。
我当然可以创建一个闭包,从函数中提取变量值。但这似乎不符合 Angular 。
最好的前进方向是什么?
最佳答案
您需要学习如何与黑白指令和 Controller 进行通信
首先,您需要创建一个单独的指令作用域,并允许它使用 '=','@'
等访问 Controller 作用域中的数据。
假设你的html是这样的:
<div>
<timeline candidates="candidates"></timeline>
</div>
还有你的 JavaScript:
app.directive('timeline', function () {
return {
scope:{
candidates:"="
},
link:function (scope, element, attrs) {
scope.$watch('candidates', function() {
var events = scope.candidates;
console.log(events);
})
}
}
})
好Example 了解有关指令的更多信息 documentation
关于angularjs - 如何通过服务请求和指令使用 Angular 作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636427/