Angular Scope inside script

旧巷老猫 提交于 2019-12-20 19:44:07

问题


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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/13836765/angular-scope-inside-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!