javascript 脚本内的角度范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13836765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:54:26  来源:igfitidea点击:

Angular Scope inside script

javascriptangularjsjavascript-framework

提问by Chubby Boy

Can we use the angular variables defined in scope inside script tag like below.

我们可以使用在脚本标签内的作用域中定义的角度变量,如下所示。

HTML CODE:

HTML代码:

<div ng-controller="AngularCtrl">
 <script>
  alert($scope.user_name);
 </script>
</div>

JS CODE:

JS代码:

function AngularCtrl($scope){
 $scope.user_name = 'John';
}

I just get '$scope is not defined'. Can someone help me with what i am doing wrong here?

我只是得到'$scope 未定义'。有人可以帮助我解决我在这里做错的事情吗?

回答by Supr

No you can't. $scopeis only defined insideAngular, i.e. within your AngularCtrl-function. There are ways to get access to angular scopes from the outside, but that's usually bad practice and a sign that you're not using Angular correctly.

不,你不能。$scopeAngular 内定义,即在您的AngularCtrl-function 内。有多种方法可以从外部访问 angular 范围,但这通常是不好的做法,并且表明您没有正确使用 Angular。

A more angulariffic way to do what you're trying is to make the alerting a part of the controller-logic:

做你正在尝试的一种更有角度的方法是使警报成为控制器逻辑的一部分:

function AngularCtrl($scope) {

    $scope.user_name = 'John';

    $scope.sayHi = function(){
        alert('Hi ' + $scope.user_name);
    }
}

You can then use a variety of angular-techniques (Demo Here) to call that sayHi()function. Some examples:

然后,您可以使用各种角度技术(Demo Here)来调用该sayHi()函数。一些例子:

In response to a click

响应点击

<div ng-click="sayHi()">Demo clickable - Please click me</div>

Automatically once when a given element is created/initialized

创建/初始化给定元素时自动执行一次

<div ng-init="sayHi()">Demo ng-init</div>

Directly from the controller when it is initialized

初始化时直接从控制器

function AngularCtrl($scope) {

    $scope.user_name = 'John';

    $scope.sayHi = function(){
        alert('Hi ' + $scope.user_name);
    }

    // Call it
    $scope.sayHi();
}

Hopefully these examples are inspiring, but what you really should do depends on what you are really trying to accomplish.

希望这些例子是鼓舞人心的,但你真正应该做什么取决于你真正想要实现的目标。