How To Pass Values Calculated By A Controller Function As Arguments To A Directive From HTML?

- 1 answer

Angular Newbie Question:

I would like to run a function myFunc within my AngularJS controller (myController) that calculates some values aB and aC.

I then want to have my HTML send those calculated values to a directive myDirective as arguments. How can I do it? I assumed attaching those values to the scope would work well.

The code below doesn't work.

The first problem I have is that I don't know when and how should I call myFunc. When it comes to line #7 in the HTML, I want myFunc to already have been run. How do I do that?

My second (and bigger) problem is that even when the values of aB and aC are calculated by myFunc, attached to the scope and passed in through the HTML as arguments to myDirective, the console.log lines #21 & #22 in that directive still report them as undefined. Why? The strange thing is they get rendered on the screen anyway by the template: 'aB={{aB}} aC={{aC}}'. How can that even happen??

This behavior is made even more confusing because when I send in literal values as arguments to myDirective in line #6 of the HTML, it works perfectly. The console.log lines #21 & #22 report them correctly. Why the difference?


 1  <body ng-app="myApp">
 2    <div ng-controller="MyCtrl">
 3      <div ng-view></div>
 4      <ul>
 5        <li>{{1+1}}</li>
 6        <li><my-directive a-b="null" a-c="'Goodbye'"></my-directive></li>
 7        <li><my-directive a-b="arguments.scopeAB" a-c="arguments.scopeAC"></my-directive>  </li>  
 8      </ul>
 9    </div>
10  </body>

My JavaScript:

11  myApp = angular.module('myApp',[]);
12  myApp.directive('myDirective',function(){
13      return {
14          restrict:'E',
15          scope: {
16              aB: '=',
17              aC: '='
18          },
19          link: function(scope, element, attrs) {
20              console.log('scope = ', scope);
21              console.log('scope.aB = ', scope.aB);
22              console.log('scope.aC = ', scope.aC);
23          },
24          template: 'aB={{aB}} aC={{aC}}'
25      };
26  });
27  myApp.controller('MyCtrl', function($scope) {
28      var self = this;
30        self.myFunc = function(response) {
31          scope.arguments.scopeAB = 'Hello';
32          scope.arguments.scopeAC = 'World';
33        }
34      }
35  );

Here is the JSFiddle



Your code has some syntax errors which are causing your controller to not be initialized:

<div controller="myCtrl"> should be ng-controller and MyCtrl to match up with your controller definition, i.e. <div ng-controller="MyCtrl">

With those changes to the HTML, the following controller will properly set the values inside the directive:

myApp.controller('MyCtrl', function($scope) {
  console.log('Controller\'s  function initializing some values on the Scope');
  $scope.scopeAB = 'Hello';
  $scope.scopeAC = 'World';