为什么不是在视图或控制器中显示的指令中定义的范围变量?

时间:2016-04-04 07:13:05

标签: angularjs directive

我使用指令获取数据并创建范围变量' services'但它没有显示在视图中,而且在控制器中它未被定义。'数据展示的最佳方式是什么?

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>

1 个答案:

答案 0 :(得分:1)

您是否在指令中尝试过此操作?

$scope.$parent.services = services;

然后在你的控制器中:

console.log($scope.services);

希望它可以提供帮助。