里面的脚本角范围 [英] Angular Scope inside script
问题描述
我们可以使用的范围定义的脚本标签中像下面的角度变量。
Can we use the angular variables defined in scope inside script tag like below.
HTML code:
HTML CODE:
<div ng-controller="AngularCtrl">
<script>
alert($scope.user_name);
</script>
</div>
JS code:
JS CODE:
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?
推荐答案
没有你不能。 $范围
只被定义的在的角,即你的 AngularCtrl
- 函数中。有办法可以访问从外部的角度范围,但是这通常是不好的做法,并且你没有使用正确角度的标志。
No you can't. $scope
is only defined inside Angular, 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.
一个更angulariffic的方式做你想要的是让报警控制器逻辑的一部分:
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);
}
}
然后,您可以使用各种角度的技术(演示这里)来调用的sayHi()
功能。一些例子:
You can then use a variety of angular-techniques (Demo Here) to call that sayHi()
function. Some examples:
<div ng-click="sayHi()">Demo clickable - Please click me</div>
自动一旦当创建一个给定的元素/初始化
<div ng-init="sayHi()">Demo ng-init</div>
当它被初始化
直接从控制器
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.
这篇关于里面的脚本角范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!