Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

angularjs - app.controller vs function in angular.js

I'm learning angular.js, and wonder when app.controller("MyCtrl",...) should be used and when function MyCtrl($scope){...} should be used.

I see no big differences between the two approaches in this example (link to a plunker):

index.html:

<body ng-app="myApp">

    <div ng-controller="FirstCtrl as app1">
        <button class="btn" ng-model="app1.count"
                            ng-click="app1.increment()">
        Click to increment</button>
        {{ app1.count }}
    </div>

    <div ng-controller="SecondCtrl">
        <button class="btn" ng-model="count"
                            ng-click="increment()">
        Click to increment</button>
        {{ count }}
    </div>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
    <script type="text/javascript" src="example.js"></script>
</body>

example.js:

var app = angular.module("myApp", []);

app.controller("FirstCtrl",function () {
    this.count = 0;
    this.increment = function (){
        this.count = this.count + 1;
    }
});

function SecondCtrl($scope){
    $scope.count = 0;
    $scope.increment = function (){
        $scope.count = $scope.count + 1;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The major reasons for using the module based controller declaration are

  • Support for minification. The second approach breaks when you minify the code as Dependency Injection fails.
  • JavaScript good practice is to minimizing polluting the global namespace and the first syntax help there.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...