2016-07-30 7 views
0

가능한지 물어보고 싶은 경우 컨트롤러에서 지시문에 일부 변수를 전달할 수 있습니까? 여기 는 내 코드의 비트 : 나는 지시어에 사용하기 위해 필요한이 내가 DB에서 일부 데이터를 얻으려고 app.js에서컨트롤러에서 지시어로의 AngularJS 변수

var VirtualGallery = angular.module('virtualGallery', ['VirtualGalleryControllers', 'ngRoute']); 

VirtualGallery.constant('apiURL', 'roomPicture'); 

VirtualGallery.run(['$rootScope', function ($rootScope) { 
    $rootScope.roomPictures = []; 
}]); 

var VirtualGalleryControllers = angular.module('VirtualGalleryControllers', ['ngRoute']); 

VirtualGalleryControllers.controller('AppCtrl', function ($http, $rootScope, $scope, apiURL, $q) { 
$scope.getallrooms = function() { 
    $http.get(apiURL) 
     .success(function (data) { 
      $rootScope.roomPictures = data; //idk whether to use $scope or $rootScope 
     }); 
    }; 
}); 

을 app.js, 해당 데이터 . 지시문

지침

angular.module('virtualGallery') 
    .directive('ngWebgl', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      'getallrooms': '=', 
      'roomPictures': '=' 
     }, 
     link: function postLink(scope, element, attrs) { 
      scope.init = function() { 
       //here I would like to be able to access $scope or $rootScope from app.js file. 
      }; 
      } 
     }; 
    }); 

가 난 데이터를 사용할 필요 기능 초기화()에서 $ 범위에 접근 또는 $ rootScope을 얻을 필요가있다. HTML에서

HTML

<body ng-app="virtualGallery"> 
<div class="container" ng-controller="AppCtrl"> 

<div 
    id="webglContainer" 
    ng-webgl 
    getallrooms="getallrooms" 
    roomPictures="roomPictures" 
    ></div> 
    <p ng-model="roomPictures"></p> 
    <p ng-model="getallrooms"></p> 
</div> 
<script type="text/javascript" src="js/vg.js"></script> 
<script type="text/javascript" src="js/ngWebgl.js"></script> 

나는 지시어하는 app.js에서 해당 데이터를 전달하기 위해 노력하고있어.

Im은 Angular에 새롭고 첫 번째 지시어이기도하므로 조금 혼란 스럽습니다. 모든 도움을 주시면 감사하겠습니다. 고마워요 :)

답변

1

는 지시를 위해 그런 다음이

VirtualGalleryControllers.controller('AppCtrl', function ($http, $rootScope, $scope, apiURL, $q) { 
$scope.getallrooms = function() { 
    $http.get(apiURL) 
     .success(function (data) { 
      $scope.roomPictures = data; //use $scope instead of $rootScope 
     }); 
    }; 
}); 

같은 컨트롤러를 사용합니다.

+0

감사합니다. http 요청을 지시어로 옮겼습니다. 그리고 효과가있었습니다. 나는 그것이 내가 원하는 것을 할 것이라는 점을 희망한다 : – marek

+0

그리고 나는 1 개의 질문이 더있다. 이제 http 요청으로 데이터를 얻었을 때, 어떻게이 데이터를 html.file (템플릿)에 전달할 수 있습니까? – marek

+0

범위에 데이터를 추가하고 이중 중괄호 또는 ng-bind를 사용하여 각도 변수로 액세스하면됩니다. –

1

(컨트롤러에서했던 것처럼) 지시문에 $ rootScope를 삽입 한 다음 해당 rootScope 변수에 액세스 할 수 있습니다.

angular.module('virtualGallery') 
.directive('ngWebgl', function() { 
    return { 
    restrict: 'A', 
    scope: { 
     pictures: '=virtualGallery' 
    }, 
    link: function postLink(scope, element, attrs) { 
     scope.init = function() { 
      // you can access the variable through the scope 
      scope.pictures; 
     }; 
    } 
    }; 
}); 

또는 당신은 단순히 당신의 지시에 HTTP 요청을하고이 데이터를 조작 할 수있다 : 당신의 app.js에서

관련 문제