简体   繁体   English

角度指令控制器范围

[英]Angular directive controller scope

I'm trying to develop a directive that has it's own controller so it can collect the data it need's from the API and be injected anywhere. 我正在尝试开发一个具有其自己的控制器的指令,以便它可以从API收集所需的数据,然后将其注入到任何地方。

Here's what I got so far: 这是到目前为止我得到的:

(function () {
'use strict';

angular
    .module('app.hostelsmg.bookings')
    .directive('bookingsChart', bookingsChart);

function bookingsChart() {
    return {
        restrict: 'E',
        scope: true,
        controller: [function(){
            $scope.test = 'Hi there!';
        }],
        compile: function(tElem, attrs){
            tElem.html('{{test}}');
            return function(scope, elems, attrs){

            }
        }
     }
 }
})();

So what I'd like, is the directive to get data from it's own controller. 所以我想要的是从其自己的控制器获取数据的指令。 So far I couldn't get it to work that way. 到目前为止,我还无法以这种方式工作。

Does anyone know how? 有人知道吗?

You can use something like this 你可以用这样的东西

function bookingsChart() {
    return {
        restrict: 'E',
        scope: true,
        controller: ['$scope', 'yourservice', function ($scope, yourservice) {
            $scope.data = [];   //bind this data to your view

            $scope.getServiceData = function (count) {
                //your service call
                yourservice.getServiceData(count).then(function (data) {
                    $scope.data = data;  //sets data in $scope.data variable
                });
            }
        }],
        link: function (scope, elements, attributes) {
            //if you want to pass any parameters from your UI to your service method
            scope.getServiceData(attributes.count);    //calls the getServiceData in controller defined above 
        }
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM