【问题标题】:How to Access Internal script $scope value in controller function in angular JS如何在 Angular JS 中访问控制器函数中的内部脚本 $scope 值
【发布时间】:2025-11-24 10:25:01
【问题描述】:

这是带有内部脚本的 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 打印或绑定数据,它不会在控制器范围对象中更新。有什么解决办法吗?

【问题讨论】:

  • 我认为您的控制器代码将首先运行,然后是您的外部代码以更新您的范围。那么如何定义您当前记录的值呢?

标签: javascript angularjs angularjs-scope angular-controller


【解决方案1】:

您是否尝试从控制器中获取它?或者,也许您将需要更多 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>

【讨论】: