javascriptangularjsangularjs-directiveangularjs-scopeangularjs-ng-transclude

can't pass dynamic parameter to angular directive


I just took over the frontend work of our angularjs apps and I'm stuck.

I've been creating directives to replace bloated html to make updating the frontend look easier. All was going well till I hit the voting page of our elections app.

directive passing param (none work)

 <div block-container header="vm.electionToVote.name" startrow="'false'">
 <div block-container header="'vm.electionToVote.name'" startrow="'false'">
 <div block-container header="{{vm.electionToVote.name}}" startrow="'false'">

usually these work

<div block-container header="'Elections List'">
<div block-container header="vm.full.title" startrow="'false'">

directive html <h3>{{style.header}}</h3>

directive

.directive('blockContainer', blockContainer);
    /* @ngInject */
    function blockContainer() {
        var directive = {
            scope: {
                header: '=',
                startrow: '='
            },
            replace: true,
            transclude: true,
            controller: blockContainerCtrl,
            controllerAs: 'style',
            templateUrl: 'app/style/directives/blockContainer.tpl.html',
            restrict: 'A'
        };
        return directive;
        function blockContainerCtrl($scope) {
            //debugger;
            var vm = this;
            vm.header = $scope.header;
            vm.startrow = angular.isDefined($scope.startrow) ? $scope.startrow : 'true';
        }
    }

running debug shows that vm.electionToVote is undefined but ng-inspector shows that is has stuff (id, name, endDate etc) screenshot: https://i.sstatic.net/lXn5U.png

you can see all (including election) files here: https://plnkr.co/edit/bPVp8QY0xzlJ6aWZoRDi?p=preview

I'm really an angualjs beginner, but with google, stackoverflow and a lot of trial and error, I'm getting the job done... sort of...

any other tips/advice would be greatly appreciated as well


Solution

  • As you have used style.header on HTML to bind header value on HTML, you should add bindToController: true in your directive so that all the isolated scope bindings will be available inside your directive html.

    Directive

    var directive = {
        scope: {
            header: '=',
            startrow : '='
        },
        replace: true,
        transclude: true,
        controller: blockContainerCtrl,
        controllerAs: 'style',
        templateUrl: 'app/style/directives/blockContainer.tpl.html',
        restrict: 'A',
        bindToController: true //<-- Added this line
    };
    

    Directive Usage

    <div block-container header="vm.electionToVote.name" startrow="'false'">
    

    Additionally you should not be doing header & startrow variable assignment inside controller manually. Removing those two assignment part would make it work.