theHussle
theHussle

Reputation: 321

Trouble binding value from script to angular value

Fairly new to Angular and playing around with binding a value calculated from a script to an angular model for display, for some reason I can't get it to show.

<!DOCTYPE html>
<html>
   <head>
      <base href="." />
      <title>modern Angular 1 playground</title>
      <link rel="stylesheet" href="style.css" />
      <script src="https://unpkg.com/[email protected]/dist/system.js"></script>
      <script src="config.js"></script>
      <script>
         System.import('app')
           .catch(console.error.bind(console));
      </script>
   </head>
   <body>
      <my-app>
         loading...
      </my-app>
      <script>
         $scope.localDate = function() {
             var currentTime = new Date();
             var year = currentTime.getFullYear();
             var month = currentTime.getMonth();
             var day = currentTime.getDate();
             var date = new Date(Date.UTC(year, month, day));
             var localDate = date.toLocaleDateString();     
             return $scope.localDate;
         }

         console.log(localDate);
      </script>
      <p ng-model="localDate.localDate">Date = {{localDate}}</p>
   </body>
</html>

plnkr link

http://plnkr.co/edit/DOAbtwhIpLxzAJOoCxID

Upvotes: 0

Views: 36

Answers (1)

K Scandrett
K Scandrett

Reputation: 16541

You won't be able to access $scope outside of <my-app> because that is the root of the Angular application.

What you can do is remove the reference to $scope from your global function and then call that function in AppComponent:

localDate = function() {

  var currentTime = new Date();
  var year = currentTime.getFullYear();
  var month = currentTime.getMonth();
  var day = currentTime.getDate();

  var date = new Date(Date.UTC(year, month, day));
  var localDate = date.toLocaleDateString();

  return localDate;
}

and

export const AppComponent = {
  template: `
    <div>
      <h2>Hello {{ $ctrl.name }}</h2>
      <p>Date = {{ $ctrl.localDate }}</p>
    </div>
  `,
  controller: class AppComponent {
    $onInit() {
      this.name = 'modern Angular 1'  
      this.localDate = localDate();
    }
  }
};

Example: http://plnkr.co/edit/qTsTbpgEyco4shiKwRSx

Upvotes: 1

Related Questions