AngularJS Set Value to $scope from Nested Function

1.8k Views Asked by At

I'm trying to get a value from a function inside a function:

Controller

  $scope.vm = {};

  function myFunc(){
    $scope.vm.hello = 'Hello';
    function myFunction(){
      $scope.vm.world = 'world';
    }
  }

  myFunc();

View

<p>{{vm.hello}} {{vm.world}}</p>

Here's my Plunk.

How can I get this to display "Hello world"?

1

There are 1 best solutions below

0
On BEST ANSWER

I assume that you are trying to achieve something called 'closure'. If so, modify your controller to:

app.controller('MainCtrl', function($scope) {

  $scope.vm = {};

  function myFunc(){
    $scope.vm.hello = 'Hello';
    return function () {
      $scope.vm.world = 'world';
    }
  }

  var hello = myFunc(), // invokes outer function
      world = hello();  // invokes inner function

  console.log($scope.vm);      
});

In your code, the inner function myFunction() cannot be called outside the myFunc() method, because its scope is bounded by this outer method. You can of course call it directly inside outer method, or better - make the inner function immediate:

  function myFunc(){
    $scope.vm.hello = 'Hello';
    (function myFunction(){
      $scope.vm.world = 'world';
    })();
  }