{{data.name}} {{data.name}} {{data.name}}

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

99 views Asked by At

Here is HTML with internal script

 <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>

Here is Controller

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

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

 })

I want internal script data into the controller. It prints undefined. I defined an object in the controller but updated in the internal script. If suppose I print or bind data from HTML, it does not get updated in the controller scope object. Any Solution for this?

1

There are 1 answers

0
gabriella-varga On

Did you try to fetch it from the controller? Or maybe you will need a more angularjs approach. I created two examples: one for initializing the data in the controller, and one to console.log the 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>