admin管理员组文章数量:1225015
Can we use the angular variables defined in scope inside script tag like below.
HTML CODE:
<div ng-controller="AngularCtrl">
<script>
alert($scope.user_name);
</script>
</div>
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?
Can we use the angular variables defined in scope inside script tag like below.
HTML CODE:
<div ng-controller="AngularCtrl">
<script>
alert($scope.user_name);
</script>
</div>
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?
Share Improve this question asked Dec 12, 2012 at 9:36 Chubby BoyChubby Boy 31.1k19 gold badges48 silver badges47 bronze badges1 Answer
Reset to default 15No 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.
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:
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.
本文标签: javascriptAngular Scope inside scriptStack Overflow
版权声明:本文标题:javascript - Angular Scope inside script - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739440417a2163216.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论