1290 1290 - 1 year ago 86
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


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'

) looks something like this:

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



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

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

Answer Source

@ 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.


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

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



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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download