Search code examples
angularjsangularjs-scopeangularjs-ng-click

How To Pass Template-Defined Variable to Angular Controller


This question is a long overdue extension of Angularjs How to pass parameter back to controller from directive with ng-click in which strings are able to be passed to an Angular controller, but variables defined in the template are not.

In this JSFiddle 'string' is passed through to the controller, and var foo is 'undefined'.

index.html:

<div ng-app>
  <div ng-controller="YourController">
    <button type="button" ng-click="showString(foo)">One</button>
    <button type="button" ng-click="showString('Two')">Two</button>
    <p>Result: {{string}}</p>
  </div>
</div>

<script>
    var foo = "bar";
</script>

main.js:

function YourController($scope) {
    $scope.string='';
  $scope.showString = function (provider) {
    $scope.string= provider;
  }
}

(First Stack Overflow post here.. go easy on me ;))


Solution

  • Found a solution, here's the updated JSFiddle.

    1) In index.html, I changed

    <script>
      var foo = "bar";
    </script>
    

    to

    <script>
      window.foo = "bar";
    </script>
    

    2) In main.js, I added

    $scope.foo = window.foo;
    

    Feel free to comment if there are better solutions.