Search code examples
angularjsangularjs-directiveangularjs-scope

AngularJS directive scope property doesn't render in directive view


I have a problem with scope property of directive that doesn't render want to render in directive view.

app.js

.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })

main.js

angular.module('todayfmApp')
    .controller('MainCtrl', ['$scope', function ($scope) {

        this.formsetup = [];

        this.formsetup.title = "Find Your Break";

    }]);

mainController View - where Form Setup: {{main.formsetup.title}} is rendering properly

<h2>Form Setup: {{main.formsetup.title}}</h2>
<section class="home-banner">

    <carousel-partial></carousel-partial>

    <overlay-form formsetup="main.formsetup.title"></overlay-form>

directive

angular.
    module('directives').
    directive('overlayForm', function() {
        return {
            restrict: 'E',
            scope: {
                formsetup: '='              
            },
            controller: [ '$http', '$scope',
                function OverlayFormController($http, $scope) {

                    var self = this;

                    self.getResponseData = function(){
                        $http.get('data/form-data.json').then(function(response) {
                            self.formdata = response.data;                          
                        });
                    }

                    this.logResponseData = function() {
                        console.log(self.formdata);
                    }

                    this.getResponseData();
                }
            ],
            controllerAs: 'Ctrl',
            bindToController: true,
            templateUrl: 'scripts/directives/overlay-form/overlay-form.template.html',
        };
    });

Directive View

<div class="overlay-form">
  <h3>{{formsetup.title}}</h3>

Solution

  • Problem is with template binding.It should be:(when you use controllerAs you need to refer view elements with the alias name)

    <div class="overlay-form">
      <h3>{{Ctrl.formsetup.title}}</h3>
    </div>
    

    And directive HTML code should be:

    <overlay-form formsetup="main.formsetup"></overlay-form>
    

    Please check Plunker for more understanding of how it works.