0

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.

1 Answer 1

1

In the controller, use injected $scope.

        controller: function ($scope) {
            //USE $scope
            console.log($scope.listId);
            //
            //console.log(scope.listId);
Sign up to request clarification or add additional context in comments.

2 Comments

inspite i have tried this and it didn't work. Its working right now. Thanks anyway.
@h.salman you should have post your own answer and accept it as answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.