1290 1290 - 4 months ago 26
Javascript Question

AngularJS Isolated Scope Directive

I have a problem with setting the isolated scope of a directive on a Angular App:

Here is my

app.js
:

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

app.controller('mainController', ['$scope', function($scope) {
if ($scope.name == 'bob') {
console.log("It's bob")
}else if ($scope.name == 'joe') {
console.log("It's joe")
}else if ($scope.name == 'mary') {
console.log("It's mary")
}
}]);

app.directive('test', function() {
return {
restrict : 'E',
replace : true,
templateUrl : 'test.html',
scope: {
name : '@'
}
controller : 'mainController'
};
});


(
Main.html
) looks something like this:

<div ng-controller="mainController">
<div>
/* This is where I set the name in the directive */
<test name="bob"></test>
</div>
</div>


Test.html
:

<div>{{name}}</div>


Now for some reason when I run the above
HTML
code none of the print statements happen in my mainController.

If I set a custom scope object in the
directive
does that mean the directive
test
doesn't have access to the
mainController
which is the controller I passed in to the directive under the
controller
key.

Answer

@ binding is for passing strings. These strings support {{}} expressions for interpolated values. For example: . The interpolated expression is evaluated against directive's parent scope.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope. Changes to one model affects the other, and vice versa.

Please find a working code example below - with a Fiddle link.

VIEW

<!doctype html>
<html ng-app="app">

  <body ng-controller="appController">
    <ul ng-repeat="item in names">
      <test name='item.name'></test>
    </ul>
  </body>

</html>

CONTROLLER & DIRECTIVE

var app = angular.module('app', [])


app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '='
    },
    controller: 'nameController',
    template: '<div>{{name}}</div>'

  }
})

app.controller('appController', ['$scope', function($scope) {
  $scope.names = [{
    'name': 'mary'
  }, {
    'name': 'joe'
  }, {
    'name': 'bob'
  }, {
    'name': 'abraham'
  }];

}]);

app.controller('nameController', ['$scope', function($scope) {
  if ($scope.name == 'bob') {
    console.log("It's bob")
  } else if ($scope.name == 'joe') {
    console.log("It's joe")
  } else if ($scope.name == 'mary') {
    console.log("It's mary")
  }else {
    console.log("It's someone else")
  }
}]);

Have a look at the Fiddle