从简单的JavaScript代码访问AngularJS $ scope变量

时间:2018-01-29 10:39:07

标签: javascript html angularjs

这似乎与

重复

AngularJS access scope from outside js function,因为我不想在任何点击时访问此变量!

我的Maincontroller.js中的AngularJS代码是

<div ng-controller = "Maincontroller">
   $scope.name = "Hello";
</div>

在我的main.HTML文件中,我有JavaScript代码,我希望这个$scope.name值:

 <html>
       <script>
          // But this seems not possible with {{ name}}
       </script>
 </html>

是否有可能在JavaScript代码中访问此$scope变量?

1 个答案:

答案 0 :(得分:0)

请检查下面的代码。我做的是我在UI上发布了这个名字,在id的帮助下,我借助getElementById和innerHTML从javascript代码中获取了值。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
</head>
<body >
    <div ng-app="app" ng-controller="Maincontroller">
        Angualr Scope: <h1 id="name">{{name}}</h1>
    </div>

    <div>
        A button to call a function from simple javascript function: <button onclick="getData()">Get Data: </button>        
    </div>

    <script src="../lib/angular.js"></script>

    <script>
        var getData = function(){
            var name = document.getElementById('name');
            console.log(name.innerHTML);
        }
    </script>

    <script>
        var app = angular.module('app', []);
        app.controller('Maincontroller', function ($scope) {
            $scope.name = "Hello";
        });
    </script>
</body>
</html>