gpt4 book ai didi

Angular js 之外的 JavaScript

转载 作者:行者123 更新时间:2023-11-28 00:06:37 24 4
gpt4 key购买 nike

在 Angular JS 中,我可以在 Controller 外部创建 Javascript 函数并在需要时调用它,而不是在模块中使用服务吗?

例如:

var UrlPath="http://www.w3schools.com//angular//customers.php"
//this will contain all your functions
function testing_Model ($http){
var self=this;

self.getRecords=function(){
$http({
Method:'GET',
URL: UrlPath,
}).success(function(data){
self.record=data.records;
});

}
self.getRecords();
}

angular.module("myApp", []);
app.controller('myController', function ($scope, $http) {
$scope.testing_Model = new testing_Model();}

当我运行上面的代码时,它显示“$http 不是一个函数”。

提前致谢。

最佳答案

您需要将 $http 传递给此函数...

$scope.testing_Model = new testing_Model($http);

尽管它可以工作,但显然违背了 Angular 的理念。您必须将函数作为服务注入(inject) Controller 中,以编写可测试的代码、跟踪依赖项并尊重稍后将支持您的项目的其他开发人员。

关于Angular js 之外的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31288112/

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