Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angularjs - Difference between this and scope in the controller

I'm new to angularjs. What is the difference if You assign function to $scope or this keywords in the controller? Thank You.

Example (scope):

.controller('TestCtrl', ['$scope', function ($scope) {
    $scope.testFunc = function () {
    };
}]);

Example (this)

.controller('TestCtrl', [function () {
    var app = this;
    app.testFunc = function () {
    };
}]);
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

$scope is a core concept of angular framework and dual data-binding functionnalities. Its for example, designed to share its content with :

  • templates
  • directives
  • etc

In a template for example, you'll need to bind a function to the scope to access it. You'll not be able to call a function binded on this directly.


Edit: Thank to BKM post that pointed out that this behavior is possible with the "controller as" syntax which binds your template directly to the controller. But it's up to you to decide if you want to let access all objects/variables of your controller in your template instead of having a dedicated viewModel (scope). For pros and cons, see : https://groups.google.com/forum/#!topic/angular/84selECbp1I


It's an important concept of angular that you need to understand.

See :

this keywork refers only the the javascript object refering to your controller, nothing more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...