2016-07-30 28 views
0

もし可能であれば、私はあなたに質問したいと思います。もしそうなら、どのようにコントローラからディレクティブにいくつかの変数を渡すことができます。ここ は、私のコードのビットです:この中コントローラからディレクティブへの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は私がDBから一部のデータを取得しようとしている、そのデータ私はディレクティブで使用する必要が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. 
      }; 
      } 
     }; 
    }); 

は、私はそのデータを使用する必要がある関数init()で$スコープへのアクセスまたは$ 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からそのデータを渡すためにしようとしています。

私は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

そしてもう一つ質問がある。 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で

関連する問題