Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access controller scope from directive

This is my app config:

angular.module('myApp', ['myApp.directives', 'myApp.controllers', 'myApp.services']);

This is my controller:

angular.module('myApp.controllers', [])
  .controller('MainCtrl', function ($scope) {
      $scope.name = 'world';
  });

This is my directive:

var directives = angular.module('myApp.directives', []);

directives.directive("hello", function () {
    return function (scope, elm, attrs) {
        elm.text("hello, " + scope[attrs.name]);
    };
});

and this is my html:

<div ng-controller="MainCtrl">
    <h1 hello></h1>
</div>

The is problem is that angular render the directive as:

hello, undefined

Instead of:

hello, world

What is wrong?

like image 362
Yair Nevet Avatar asked Dec 24 '12 14:12

Yair Nevet


1 Answers

You are accessing scope[attrs.name] but the directive doesn't provide a value for the attribute name

There are 2 options:

  1. Change the directive to elm.text("hello, " + scope['name']); This is not a preferred way as it hard codes to a scope property name

  2. Change the html to <h1 hello name="name"></h1>. This is better but I feel it uses a redundant attribute

I would suggest you change the directive to elm.text("hello, " + scope[attrs['hello']]);

Or even better elm.text("hello, " + scope.$eval(attrs['hello']));

this way you get the benefit of expressions as well(ex: <h1 hello="name|uppercase"></h1>) demo

This way the html would be <h1 hello="name"></h1>

Regarding the attrs parameter: it's nothing more than a map of strings taken from the attributes present on the dom element.

like image 161
Liviu T. Avatar answered Oct 20 '22 07:10

Liviu T.