gpt4 book ai didi

angularjs - 将 3rd-party Javascript 库包含到 AngularJS 应用程序中

转载 作者:行者123 更新时间:2023-12-03 08:49:52 24 4
gpt4 key购买 nike

我正在尝试在我的 AngularJS 应用程序中包含一个 javascript 库(实际上是一小部分)。到目前为止,我正在构建这个应用程序的精简版,没有设计。在这一点上,它只是关于功能和数据处理。

这是我尝试添加到我的 AngularJS 应用程序中的第一个 javascript 库:https://github.com/LarryBattle/Ratio.js

起初,我尝试使用 script src 标签将它简单地包含到我的 HTML 文件中,但是当我尝试在我的 Controller 中使用它时,我收到此错误:ReferenceError: require is not defined

我读过最好在使用 AngularJS 时将 javascript 库转换为服务或指令甚至过滤器。任何人都可以提供有关执行此操作的最佳方法的任何见解吗?或者一些相关的教程?我一直无法找到一种足够简单的方法来满足我的需求。任何人都可以帮助或提供一些指导吗?到目前为止,这是我的代码:

<html ng-app="myApp">
<head>
<title>PercentCalc App</title>
</head>
<body ng-controller="MainCtrl">

Amount: <input type="number" ng-init="amountone=28" ng-model="amountone"> Value: <input type="number" ng-init="valueone=300" ng-model="valueone">
<br />
Amount: <input type="number" ng-init="amounttwo=3.5" ng-model="amounttwo"> Value: <input type="number" ng-init="valuetwo=50" ng-model="valuetwo">
<br /><br />
=========================
<br /><br />
Test ratio: {{ amountone }}/{{ amounttwo}} = {{ ratioone() }} OR {{ ratioonestring }}<br />
Test ratio: {{ amounttwo }}/{{ amountone}} = {{ ratiotwo() }}<br />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="js/ratio.js"></script>
<script type="text/javascript" src="js/percentcalc-ng-one.js"></script>

</body>
</html>

===
//percentcalc-ng-one.js
'use strict';

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope) {
console.log($scope);
var Ratio = require("lb-ratio"); // <--- this is where the error is thrown
$scope.ratioone = function () { return $scope.amountone / $scope.amounttwo; }
$scope.ratiotwo = function () { return $scope.amounttwo / $scope.amountone; }

$scope.ratioonestring = Ratio.parse( $scope.ratioone() ).simplify().toString();

});

如果有人能帮助指导我如何将 3rd-party javascript 库包含到我的 AngularJS 应用程序中,我将不胜感激。我希望能够将它作为依赖项添加到某些应用程序中,这样我就可以在其他应用程序中重用此功能。提前致谢!

最佳答案

评论var Ratio = require("lb-ratio")它应该工作。

当您包含脚本时,Ratio 已经在您的全局范围内(窗口的,而不是您的 Controller )。

关于angularjs - 将 3rd-party Javascript 库包含到 AngularJS 应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com