What is $scope in AngularJS? [closed]

2019-01-30 11:32发布

问题:

I am new to AngularJS and I can't understand what $scope is in AngularJS. Can someone please explain in the simplest way possible what does $scope do in AngularJS and what can we use it for. Please explain it in a way you would explain someone with absolutely no knowledge of programming. Also can someone explain the code below line by line in the simplest way possible?

function MyController($scope) {
    $scope.username = 'World';

    $scope.sayHello = function() {
        $scope.greeting = 'Hello ' + $scope.username + '!';
    };
};

回答1:

Every controller has an associated $scope object.

A controller (constructor) function is responsible for setting model properties and functions. This can be done only through $scope. Whatever function or model you apply in View (html file), that is accessed in controller using scope.

Only methods defined on this $scope object are accessible from the HTML/view. Example - from ng-click, filters, etc.

Now Let us take your examples one by one –

1.

 function MyController($scope) {
 $scope.username = 'World';
 };

In the above example you are defining any attribute named username with its value as “World”. Suppose in the html file you have the following line of code –

<div ng-controller="MyController">
<h1>{{data.username}}</h1></div>

This will automatically pick up the value from controller and display it on screen. It is worth noting that "data." in the markup is the name of the controller that the html page can refer to the controller as. This is usually defined within the controller or at the top of the html file.

2.

$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.username + '!';
};

This is a function you have defined in a controller which you can access in view by following code –

<div ng-controller="MyController">
<h1>{{data.greeting}}</h1></div>

Here, data.greeting will automatically pick value from sayHello function i.e. the value displayed will be "Hello World". "World" from username concatenated with “Hello” before.

I hope this clears your doubt. :)



回答2:

Read The Following Manual.

In other words, scope is an "object" that "binds" to DOM element where you apply controller. All child elements can read and modify scope data (unless you modify primitives in new scopes or they're isolated).