如何从html调用javascript函数?

时间:2015-08-24 06:22:42

标签: javascript angularjs ionic-framework

我有以下代码:

<ion-content>
    <ion-list>
      <ion-item ng-repeat="x in names|orderBy:'order_id'">
        {{ x.order_id + ', ' + x.table_id+', '+x.name+', '+x.phone+', '+x.address+', '+x.remark+', '+myFunction(x.ctime)}}
      </ion-item>
    </ion-list>
  </ion-content>

我想调用myFunction并获取返回的值,但它不起作用。

<script type="text/javascript">
function myFunction(ctime) {
    alert("Hello World!");

    // create a new javascript Date object based on the timestamp
    // multiplied by 1000 so that the argument is in milliseconds, not seconds
    var date = new Date(ctime*1000);
    // hours part from the timestamp
    var hours = date.getHours();
    // minutes part from the timestamp
    var minutes = "0" + date.getMinutes();
    // seconds part from the timestamp
    var seconds = "0" + date.getSeconds();

    // will display time in 10:30:23 format
    var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
    console.log("debug",formattedTime);
    return formattedTime;
}

</script>

我想知道问题出在哪里。感谢。

1 个答案:

答案 0 :(得分:2)

您页面中附加script的顺序以及正在评估的expression可能是问题所在。

无论如何,不​​建议直接在html文件中创建全局JavaScript函数。您正在使用AngularJS,您可以在相关的scope中使用此功能,该功能会自动为您处理。

你必须在某个controller声明你的对象数组names,它必须看起来像:

myApp.controller('NamesCtrl', ['$scope', function($scope) {
  $scope.names = [{order_id: 1, table_id: 4, name: "Someone"}];
}]);

只需将myFunction添加到控制器的范围内,如:

myApp.controller('NamesCtrl', ['$scope', function($scope) {
  $scope.names = [{order_id: 1, table_id: 4, name: "Someone"}];

  $scope.myFunction = function myFunction(ctime) {
    alert("Hello World!");

    // create a new javascript Date object based on the timestamp
    // multiplied by 1000 so that the argument is in milliseconds, not seconds
    var date = new Date(ctime*1000);
    // hours part from the timestamp
    var hours = date.getHours();
    // minutes part from the timestamp
    var minutes = "0" + date.getMinutes();
    // seconds part from the timestamp
    var seconds = "0" + date.getSeconds();

    // will display time in 10:30:23 format
    var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
    console.log("debug",formattedTime);
    return formattedTime;
  };
}]);

调用函数的表达式无需更改。

如果您想了解有关此概念的更多详情,请查看here

如果您仍然选择将script保留在html页面中,您可以尝试在表达式之前包含该脚本,并检查它是否解决了问题。

如果您仍有任何问题,请随时发表评论。

相关问题