Hussein Salman
Hussein Salman

Reputation: 8256

Angularjs passing variable to a directive's controller

I am creating Angularjs Directive. However i need to pass a paramter to the directive and use it in its controller to populate its items using $http service.

i am passing a "listId" parameter to the directive, the controller inside the directive expects this parameter to retrieve items of that list from the server. The code in the controller embedded in the directive is commented.

  <script type="text/javascript">
        var app = angular.module('app', []);
        app.controller('metadataCtrl', function ($scope, $http) {

        });

        app.directive('mydirective', function ($http) {
            return {
                restrict: 'AE',
                template: '<div ng-repeat="model in items">{{ model.name}} </div>',
                replace: true,
                scope: {
                    listId: '='
                },
                controller: function ($scope) {

                    //console.log(scope.listId);
                    //  console.log(listId);
                    //$http({ method: 'GET', url: 'http://localhost:62624/home/listvalues?listid=' }).then(function (response) {
                   // $scope.items = response.data;

                    //}, function (result) { alert("Error: No data returned"); });

                },
                link: function (scope, element, attrs) {
                    console.log(scope.listId);
                }
            };
        });


    </script>

The HTML code

<body ng-app="app">


    <form name="myForm" ng-controller="metadataCtrl" class="my-form">

        <mydirective list-id="99"></mydirective>

    </form>
</body>

The listId can be accessed in the link() function in the directive (i am using console.log() to test that). However, this doesn't work in the controller function.

Upvotes: 0

Views: 34

Answers (1)

georgeawg
georgeawg

Reputation: 48968

In the controller, use injected $scope.

        controller: function ($scope) {
            //USE $scope
            console.log($scope.listId);
            //
            //console.log(scope.listId);

Upvotes: 1

Related Questions