什么是AngularJS $范围是什么? [英] What is $scope in AngularJS?

查看:124
本文介绍了什么是AngularJS $范围是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来AngularJS,我不明白是什么 $范围是AngularJS。
可有人请用最简单的方式解释可能有哪些呢 $范围做AngularJS以及我们可以使用它。请你可以解释的人,绝对没有编程知识的方式解释。还可以通过人行可能最简单的方式解释如下行code?

 函数myController的($范围){
    $ scope.username ='世界';    $ scope.sayHello =功能(){
    $ scope.greeting ='你好'+ $ scope.username +!;
};


解决方案

每个控制器都有一个相关的 $范围对象。

一个控制器(构造)函数负责设置模特属性和功能。这只能通过$范围来完成。您在View(HTML文件)适用于任何功能或模式,即在控制器应用范围进行访问。

只有这个范围$对象上定义的方法是从HTML /视图访问。示例 - 从NG-点击,滤波器等

现在让我们以一个你的一个例子 -

1

 函数myController的($范围){
 $ scope.username ='世界';
 };

在上面的例子中,你与它的世界的价值定义任何名为username属性。假设你有code以下行的文件 -

 < D​​IV NG控制器=myController的>
< H1> {{data.username}}< / H1>< / DIV>

这会自动捡起控制器的价值,并在屏幕上显示。

2

  $ scope.sayHello =功能(){
$ scope.greeting ='你好'+ $ scope.username +!;
};

这是你可以通过以下code鉴于访问您在控制器中定义的函数 -

 < D​​IV NG控制器=myController的>
< H1> {{data.greeting}}< / H1>< / DIV>

下面,data.greeting会自动从sayHello的功能,即显示的将是Hello World的价值挑值。 世界的用户名与你好之前串联。

我希望这会清除您的疑问。 :)

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 + '!';
};

解决方案

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.

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. :)

这篇关于什么是AngularJS $范围是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆