简体   繁体   中英

AngularJS Set Value to $scope from Nested Function

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"?

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';
    })();
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM