runtimeZero
runtimeZero

Reputation: 28106

Isolated scope fails to listen to changes in values

The isolated scope is setup to listen to changes in the containing scope. However this fails.

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.foo = { bar: 'hello' };

})
.directive('test-dir', function() {
  return {
    restrict: 'E',
    scope: {
      name: '='  
      },
      link: function($scope) {
        console.log($scope.name);

        $scope.$watch('name', function(newValue) {
          console.log(newValue);
        }, true);

      }
    };

});

The template is something like this:

  <body ng-controller="MainCtrl">
    <p>Hello {{foo.bar}}!</p>
    <input ng-model="foo.bar">

    <hr/>
    <testDir name='foo'></testDir>
  </body>

What am I missing here ?

Plnkr: http://plnkr.co/edit/kldjQrPPBFvlq7ZSOAeb?p=info

Upvotes: 1

Views: 24

Answers (3)

Ariel Livshits
Ariel Livshits

Reputation: 591

directive name:

.directive('testDir', function() {........

html name:

<test-dir name='foo'></test-dir>

also change in scope name to:

name: '=?'

if it doesn't work:

name: '@' 

Upvotes: 0

user1589069
user1589069

Reputation:

there should be double quotes and not single ones: name="foo", not foo

also camel case naming is used in declaration. When referring to it, you should use the dash separated names.

So when you have a directive like

directive('testDir', function() {...});

Then you use it like

<test-dir>

And not <testDir>

Upvotes: 0

Ahmed Wagdi
Ahmed Wagdi

Reputation: 934

There's nothing wrong with the scope you just mixed up the naming of your directive:

.directive('testDir', function() {...

html:

<test-dir name='foo'></test-dir>

The directive wasn't working in the first place

Upvotes: 2

Related Questions