How to access directive's controller variables in directive's template?

2.5k views Asked by At

Need to use variable (defined inside the controller element of directive) in the template element.


angular.module('home').directive('mediaTile', function(){
 return {
  restrict: "AE",
  replace: 'true',
  scope: {
   media: '=',
   displayFilter: '='
  },
  controller: function($scope){
   var vm = this;
            vm.mediaImageActual = 'img/large-tiles.png';            }
  },
  controllerAs: 'vm',
  template:  '<div>' +
     '<img preload-image ng-src="{{vm.mediaImageActual}}">' +
     '</div>'
 };
});
<div media-tile display-filter="view.displayFilter" media="dataList.lists[0]"></div>

ng-src is not getting the proper value i.e vm.mediaImageActual.

I have tried online solutions like this but unable to resolve the issue. Whats wrong ?

2

There are 2 answers

3
Developer On

Try setting bindToController: true in the directive.

You can find more details here

Use bindToController alongside controllerAs syntax, which treats Controllers as Class-like Objects, instantiating them as constructors and allowing us to namespace them once instantiated

If your are using angularJs1.6 or above, you can use component instead of directive which has all these properties set by default

3
Ram_T On

script.js

var app = angualr.module('app', []);
app.directive('mediaTile', function(){
return {
    restrict: "AE",
    replace: 'true',
    scope: {
        media: '=',
        displayFilter: '='
    },
    controller: function($scope){
        var vm = this;
        vm.mediaImageActual = 'img/large-tiles.png';
    },
    controllerAs: 'vm',
    template: '<div>{{vm.mediaImageActual}}"' +
                '</div>'
};
});

HTML

<!DOCTYPE html>
<html data-ng-app="app">
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body>
<div media-tile displayFilter="view.displayFilter" media="dataList.lists[0]"></div>
</body>

</html>