Why is the variable name “$scope” necessary ?

后端 未结 3 1277
遇见更好的自我
遇见更好的自我 2021-01-04 18:07

I\'m fairly new to Javascript ( just finished the book Eloquent Javascript ), and am currently reading AngularJS from O\'Reilly. And getting this small snippet of code to w

相关标签:
3条回答
  • 2021-01-04 18:16

    Because the Angular uses the name of the parameter in its dependency injection system, which constructs the controller.

    0 讨论(0)
  • 2021-01-04 18:22

    Both previous answers are correct , just you should know that you can "override" the default behavior if you're declaring a controller this way:

    module.controller("ControllerName",["$scope",function( custom_name ){ ... }]);
    

    Example:

    var app = angular.module("myApp",[]);
    
    app.controller("TextController",["$scope",function(glue){
        glue.name1 = "John";
        glue.name2 = "Paul";
        glue.name3 = "George";
        glue.name4 = "Ringo";
    }]);
    

    and then:

    <div ng-controller="TextController">
        Hello {{ name1 }}, {{ name2 }}, {{ name3 }}, {{ name4 }}!
    </div>
    

    Working here: http://jsfiddle.net/d4M2P/

    0 讨论(0)
  • 2021-01-04 18:34

    This is handled by the Angular injector.

    http://docs.angularjs.org/api/auto/service/$injector

    In JavaScript calling toString() on a function returns the function definition. The definition can then be parsed and the function arguments can be extracted. NOTE: This does not work with minification, and obfuscation tools since these tools change the argument names.

    http://docs.angularjs.org/guide/di

    Given a function the injector can infer the names of the service to inject by examining the function declaration and extracting the parameter names. In the above example $scope, and greeter are two services which need to be injected into the function.

    0 讨论(0)
提交回复
热议问题