首页 > 解决方案 > 如何在 Angular JS 中访问控制器函数中的内部脚本 $scope 值

问题描述

这是带有内部脚本的 HTML

 <html> 
   <body ng-controller="test">  
      <span> {{data.name}} </span>
      <input ng-model="data.name"> 
      <hidden id="test" ng-hide="true"></hidden>
   </body>
 <script> 
    var $scope = angular.element(document.getElementById('test')).scope();
    $scope.data = {
     name : test;
    };
 <script>

</html>

这是控制器

app.controller('test', function($scope) {
 $scope.data = {};

 console.log($scope.data.name)  //outputs undefined

 })

我希望将内部脚本数据输入控制器。它打印未定义。我在控制器中定义了一个对象,但在内部脚本中进行了更新。如果假设我从 HTML 打印或绑定数据,它不会在控制器范围对象中更新。有什么解决方案吗?

标签: javascriptangularjsangularjs-scopeangular-controller

解决方案


您是否尝试从控制器中获取它?或者,也许您将需要更多 angularjs 方法。我创建了两个示例:一个用于初始化控制器中的数据,另一个用于 console.log 的niceLittleValue.

(function(angular) {
  'use strict';
  var myApp = angular.module('niceExample', []);
  myApp.config(['$compileProvider', function($compileProvider) {
    $compileProvider.debugInfoEnabled(false);
  }]);
  myApp.controller('test', ['$scope', function($scope) {
    $scope.data = [];
    $scope.data.name = 'test';

    $scope.data.anotherTest = angular.element(document.querySelector('#anotherTest'));
    console.log($scope.data.anotherTest[0]);

  }]);
})(window.angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<html ng-app="niceExample">

<body ng-controller="test">
  <input ng-model="data.name" ng-model-options="{debounce: 500}">
  <span> {{data.name}} </span>
  <hidden id="test" ng-hide="true"></hidden>
  <hidden id="anotherTest" value="niceLittleValue" ng-hide="true"></hidden>
  <span> {{data.anotherTest}} </span>
</body>

</html>


推荐阅读