簡體   English   中英

從控制器到指令的AngularJS變量

[英]AngularJS variable from controller to directive

我想問你是否有可能,如果可以,那么如何將一些變量從控制器傳遞給指令。 這是我的一些代碼:

app.js

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.
             };
          }
       };
    });

在指令中,我需要在需要使用該數據的函數init()中訪問$ scope或$ rootScope。

的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>

在html中,我試圖將數據從app.js傳遞到指令。

我對Angular非常陌生,這甚至是我的第一個指令,所以我有些困惑。 每一個幫助將不勝感激。 多謝你們 :)

您可以將$ rootScope注入指令(就像在控制器中一樣),然后訪問該rootScope變量。

在您的app.js中,使用像這樣的控制器

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
        });
    };
});

然后為您的指令:

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請求並在那里處理數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM