0

Here is the HTML and Javascript for a simple Angular JS example. In this example, why didn't the link function run and set scope.flag to be true (boolean) instead of 'true' (string)?

Javascript:

angular.module('truthyTypes', [])
  .directive('myDirective', function(){
    return {
      template: '<div>flag value: {{ flag }}<br/>flag type: {{ flag | typeOf }}</div>',
      scope: {
        flag: '@'
      },
      link: function(scope){
        scope.flag = scope.flag === 'true';
      }
    }
  })
  .filter('typeOf', function(){
    return function(input){
      return typeof input;
    }
  })
;

HTML:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example78-production</title>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.1/angular.min.js"></script>
  <script src="script.js"></script>
</head>
<body ng-app="truthyTypes">
    <div my-directive flag="true"></div>
</body>
</html>

Live Example: http://plnkr.co/edit/jqk5529FmdGsxK6Xj8LZ?p=preview

Trindaz
  • 17,029
  • 21
  • 82
  • 111
  • possible duplicate of [AngularJS - Access isolated scope in directive's link function](http://stackoverflow.com/questions/17111016/angularjs-access-isolated-scope-in-directives-link-function) – Dennis Traub Sep 12 '14 at 20:56

2 Answers2

1

You are using one-way binding, hence any updates you make to the flag variable in the directive won't be propagated back to the controller.

Use two-way bindings (= instead of @), to change the flag value:

scope: {
    flag: '='
}

Inside the link function, you can then set the flag to any appropriate value, e.g.

scope.flag = true;
bengro
  • 1,004
  • 10
  • 19
0

The isolated scope is not immediately available to the link function. Please have a look at the answer to this similar question: AngularJS - Access isolated scope in directive's link function

Community
  • 1
  • 1
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108