0

I pass data from html using directive

<div ng-app="app" ng-controller="main">
   <tempdir color="red"></tempdir>
</div>

and use it

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

app.directive("tempdir", function() {
  return {
    template: "<div id={{color}}> ... </div>",
    scope: {
      color: "@"
    }
  };
});

app.controller('main', function($scope) {
  // HOW TO CONSOLE.LOG "RED"?
  console.log();
});

How to use variable color inside controller?

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34

1 Answers1

0

If the color parameter will be updated in your directive you need to use two-way binding on your directive - so instead of @ when defining your color parameter you would use =. Instead of hardcoding red for the color parameter you should instead use a controller variable.

<div ng-app="app" ng-controller="main">
   <tempdir color="selectedColor"></tempdir>
</div>

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

app.directive("tempdir", function() {
  return {
    template: "<div id={{color}}> ... </div>",
    scope: {
      color: "="
    }
  };
});

app.controller('main', function($scope) {
  $scope.selectedColor = 'red';
  console.log($scope.selectedColor);
});
Lex
  • 6,758
  • 2
  • 27
  • 42