将值从脚本绑定到角度值时出现问题



Angular 来说相当新,并且正在尝试将从脚本计算的值绑定到角度模型以进行显示,由于某种原因我无法显示它。

<!DOCTYPE html>
<html>
   <head>
      <base href="." />
      <title>modern Angular 1 playground</title>
      <link rel="stylesheet" href="style.css" />
      <script src="https://unpkg.com/systemjs@0.19.31/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链接

http://plnkr.co/edit/DOAbtwhIpLxzAJOoCxID

您将

无法访问<my-app>之外的$scope,因为这是Angular应用程序的根。

您可以做的是从全局函数中删除对$scope的引用,然后在 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;
}

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();
    }
  }
};

示例:http://plnkr.co/edit/qTsTbpgEyco4shiKwRSx

最新更新