Angular Scope inside script

后端 未结 1 958
孤街浪徒
孤街浪徒 2021-02-08 10:41

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

HTML CODE:

1条回答
  •  有刺的猬
    2021-02-08 11:22

    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

    Demo clickable - Please click me

    Automatically once when a given element is created/initialized

    Demo ng-init

    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.

    0 讨论(0)
提交回复
热议问题