1
votes

I am trying to understand how isolate scopes work, and am obviously missing something very basic. I am trying to set a scope property via a select box and then pass this property into a directive's isolate scope, but it doesn't seem to be working right.

Here's an example that summarizes my problem: fiddle link The view:

<div ng-controller="MyCtrl">
   <select name='optionfoo' ng-model='foo'>
       <option>a</option>
       <option>b</option>
    </select>
    value: {{foo}}
    <div id='dir' isolate_foo="{{foo}}" dir></div>
    <div id='dir2' foo="{{foo}}" dir2></div>
</div>

The js code:

var myModule = angular.module('myModule', [])
    .directive('dir', function () {
        return {
            restrict:'A',
            template: 'isolate foo: {{foo}}',
            scope:{               
                foo:'@isolate_foo',
            }        
        };
    }).directive('dir2', function () {
        return {
            restrict:'A',
            template: 'parent foo:{{foo}}', 
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'b';
    }]);

In the example, I have two directives - one that tries to pull in a property via isolate scope, and one that just inherits the parent scope. the 'dir2' directive seems to work as expected, whereas the 'dir' directive (the isolate scope directive) seems to actually unset the attribute that is being passed in the parent directive.

I'm sure this is a noob question, but i've spent hours searching and haven't figured out what i'm doing wrong. Any suggestions will be greatly appreciated.

Thanks!

2

2 Answers

1
votes

It's just a matter of naming convention. Replace

scope: {               
  foo:'@isolate_foo',
}

with

scope: {               
  foo:'@isolateFoo',
}

and it will work. Here's your jsFiddle with that fix applied.

The explanation for that is in the Angular docs:

Directives have camel cased names such as ngBind. The directive can be invoked by translating the camel case name into snake case with these special characters :, -, or _.

So if you define the markup as isolate_foo, Angular will, by design, map its value to a property named isolateFoo in the directive's scope.

0
votes

Here is the working example:

http://jsfiddle.net/roadprophet/SPMfT/161/

var myModule = angular.module('myModule', [])
    .directive('dir', function () {
        return {
            restrict:'A',
            template: 'isolate foo: {{foo}}',
            scope:{               
                foo:'@',
            }        
        };
    }).directive('dir2', function () {
        return {
            restrict:'A',
            template: 'parent foo:{{foo}}', 
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'b';
    }]);

EDIT

Here is a clarifying version of your issue: http://jsfiddle.net/roadprophet/SPMfT/163/