4

I have a directive and a controller according to this (it's from the Angular JS Directives PacktPub book, mostly).

angular.module('myApp',[])
.directive('myIsolatedScopedDirective', function(){
    return {
        scope : {
            'title' : '@msdTitle'
        },
        link: function ($scope, $element, $attrs) {
            $scope.setDirectiveTitle = function (title) {
                $scope.title = title;
            };
        }
    };
})
.controller('MyCtrl', function($scope){
    $scope.title = "Hello World";
    $scope.setAppTitle = function(title){
      $scope.title = title;
    };
});


<div ng-controller="MyCtrl">
    <h2>{{title}}</h2>
    <button ng-click="setAppTitle('App 2.0')">Upgrade me!</button>
    <div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}">
        <h4>{{title}}</h4>
        <button ng-click="setDirectiveTitle('bob')">Bob it!</button>
    </div>
</div>

The problem is the following: Why the <h4>{{title}}</h4> evaluate to "Hello World" and why not "I'm a directive within the app Hello World"? Can anybody explain this please? Thank you.

Plunker

1 Answer 1

5

The reason is, you have to enter the template inside directive's template property to make it the isolated one. Right now, the directive creates an isolated scope, but it doesn't use it anywhere, because the content inside your directive tag is already evaluated in the parent scope (of MyCtrl) when the directive's link function is triggered

This is probably what to want to do http://plnkr.co/edit/jmWrNpLFttDPhSooPF0M?p=preview

directive

.directive('myIsolatedScopedDirective', function(){
    return {
        scope : {
            'title' : '@msdTitle'
        },
        replace: true,
        template: '<div><h4>{{title}}</h4>' +
          '<button ng-click="setDirectiveTitle(\'bob\')">Bob it!</button>',
        link: function ($scope, $element, $attrs) {
            $scope.setDirectiveTitle = function (title) {
                $scope.title = title;
            };
        }
    };

markup

<div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}"></div>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Then I think that book is a piece of crap...So there is no way to bind the directive "content"/innerHTML (so not that one, which generated from the template!) to the directive's isolated scope? Maybe with transclude?
I haven't tried that, but transclude should maybe also do the work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.