[英]Why isn't the scope variable defined in the directive showing in the view or controller?
我正在使用指令获取数据并创建作用域变量“服务”,但该变量未在视图中显示,在控制器中未定义。 显示数据的最佳方法是什么?
var app = angular.module('myApp', []);
app.directive('myTag', ['$http', function($http, $scope) {
//http://apidocs.bookingbug.com/public.html#!/company/get_company_company_id
return {
restrict: 'E',
transclude: true,
replace: true,
scope:{
src:"="
},
controller:function($scope, $attrs){
console.info("enter directive controller");
$http({
method: 'GET',
url:$scope.src,
headers: {
'App-Id': '5a3d8b8d',
'App-Key': '738e9aca62e7465446b7be8fe4219ffa'
}
}).then(function (result) {
console.log(result);
console.log(result.data._embedded.services);
var states = result.data._embedded.services;
var services = [];
angular.forEach(states, function (state) {
var service = {
'description':state.description,
'name':state.name,
'prices':state.prices[0]
}
services.push(service)
});
$scope.services = services;
console.log($scope);
console.log($scope.services); //This shows correctly - array of objects.
}, function (result) {
alert("Error: No data returned");
});
}
}
}]).controller('MainController', function ($scope) {
console.log($scope.services); //This shows undefined
});
的HTML:
<ul class="the-results">
<li ng-repeat="service in services">
<a href="#" id="{{ $index + 1 }}">{{ service.name }}</a>, {{ service.description }}
</li>
</ul>
<my-tag src="'https://uk.bookingbug.com/api/v1/41285/services'"></my-tag>
您是否在指令中尝试了此方法?
$scope.$parent.services = services;
然后在您的控制器中:
console.log($scope.services);
希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.