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

标签 angularjs angularjs-service

我正在尝试在我的 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/

相关文章:

javascript - Angularjs:使用 ng-repeat 执行脚本

javascript - Auth0 Lock中未触发认证回调函数

javascript - Angular 服务不过滤数据

javascript - 需要存储对象,以便在刷新时,该对象应该在 angularJS 中可用?

angularjs - 如何为Tomcat服务器的angular JS应用程序配置html5模式为true

javascript - 从 Javascript 闭包函数返回一个值?

javascript - 通过 AngularJS 中的表单验证更改 css 类

javascript - AngularJS。有关服务的正确双向数据绑定(bind)的最佳实践

javascript - 这是一个伪装成工厂的 AngularJS 服务吗?

javascript - AngularFire $createUser 's promise doesn' t 返回包含用户数据的对象