簡體   English   中英

如何在 Angular JS 中訪問控制器函數中的內部腳本 $scope 值

[英]How to Access Internal script $scope value in controller function in angular JS

這是帶有內部腳本的 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 打印或綁定數據,它不會在控制器范圍對象中更新。 任何解決方案?

您是否嘗試從控制器中獲取它? 或者,您可能需要更多 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM