2014-12-22 87 views
0
pokeApp.controller('mycontroller', function($scope, $routeParams){ 


    // part 1: // why would this not work 
    $scope.myFunc();  

    $scope.myFunc = function(){ 
     console.log("Hi !"); 
    } 

    // part 2: // why would this not work 

    this.helloWorld(); 
    this.helloWorld = function(){ 
     console.log("Hello World"); 
    } 
} 

嗨 我的问题是为什么这两个东西不能工作;我的意思是要么在控制器中要么在范围内。我知道我可以调用一个简单定义的函数'function helloWorld(){...}'angularjs从控制器内部调用函数

谢谢!

回答

1

您在函数定义之前调用函数。你的代码更改为:

$scope.myFunc = function(){ 
     console.log("Hi !"); 
    } 
    $scope.myFunc(); 
+1

这与angular没有任何关系,它是关于JavaScript的。 JS是一种解释型语言,它意味着程序将逐行浏览代码,编译并执行程序。 $ scope.myFunc将不会存在,直到程序达到设定的行数为止 - 它不会向前看。 – Charlie

1

您预期的功能提升的情况发生:

myFunct(); 
 

 
    function myFunct() { 
 
     alert('hey'); 
 
    }

这会工作。

但这并不:

myFunct(); 
 

 
var myFunct = function() { 
 
    alert('hey'); 
 
}

类似的情况下发生的事情与控制器作用域属性,这正好表现为在这种情况下,一个普通的变量,意味着没有发生吊装。

你会发现这里hoising一些很好的解释:var functionName = function() {} vs function functionName() {}


因此,为了在使用提升功能你原来的代码工作的一切,它应该是这样的:

pokeApp.controller('mycontroller', function($scope, $routeParams){ 


    // part 1: 
    myFunc();  

    function myFunc(){ 
     console.log("Hi !"); 
    } 

    // part 2: 

    helloWorld(); 
    function helloWorld(){ 
     console.log("Hello World"); 
    } 
} 

或者说,有点哈克的方式来维持的范围:

pokeApp.controller('mycontroller', function($scope, $routeParams){ 


    // part 1: 
    $scope.myFunc = myFunc; // this is the key, assigns a hoisted function value 
          // to the $scope object property which is then ready 
    $scope.myFunc();  

    function myFunc(){ 
     console.log("Hi !"); 
    } 

    // part 2: 
    this.helloWorld = helloWorld; 
    this.helloWorld(); 
    function helloWorld(){ 
     console.log("Hello World"); 
    } 
} 

下面是一个片段,显示在行动中:

var myObj = {}; 
 
    myObj.f = myFunct; 
 
    myObj.f(); 
 

 
    function myFunct() { 
 
     alert('yay, it still works!'); 
 
    }

相关问题