gpt4 book ai didi

javascript - AngularJS 中的规范化 Controller

转载 作者:行者123 更新时间:2023-11-28 18:48:50 24 4
gpt4 key购买 nike

我对 AngularJS 还很陌生。我写了一段代码并且运行良好。想知道有没有办法进一步缩小 Controller 。我的index.html 文件是

<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<input type="text" ng-model="sea" ng-change="newSearch()"/>
<ul>
<li ng-repeat="x in myData">
{{ x.name + ', ' + x.emailid}}
</li>
</ul>

</div>
<script src="js/app.js"></script>
<script src="js/controllers/maincontroller.js"></script>
</body>
</html>

maincontroller.js 是

app.controller('customersCtrl', function($scope, $http) {
$http(
{
url: "http://localhost:8080/cordovaprojects/123m/www/customer.php",
method: "GET",
params: {'name':'powercom'}
})
.then(function(response) {
$scope.myData = response.data.records;
});

$scope.newSearch = function() {
$scope.newSea = $scope.sea;
$http(
{
url: "http://localhost:8080/cordovaprojects/123m/www/customer.php",
method: "GET",
params: {'name':$scope.newSea}
})
.then(function(response) {
$scope.myData = response.data.records;
});
};



});

如果您注意到我使用了相同的 $http 函数两次,但差异为 param

谢谢。

最佳答案

正如 @maurycy 在他的评论中指出的那样,保持 Controller 尺寸较小的方法是将常用功能保留在服务中。考虑这项服务:

app.service('Customers',
[ '$http',
function($http) {
return {
byName: byName
};

function byName(name) {
return $http({
url: "http://localhost:8080/cordovaprojects/123m/www/customer.php",
method: "GET",
params: {'name': name}
});
}
}
]
);

然后您可以在 Controller 中使用此服务,如下所示:

app.controller('customersCtrl', [
'$scope', 'Customers',
function($scope, Customers) {
$scope.myData = null;

Customers.byName('powercom')
.then(function(response) {
$scope.myData = response;
});
}
]);

它比您现在拥有的要短得多,而且它是分开的,使其能够在应用程序的任何其他部分中使用(并且更容易测试)。如果端点发生变化,您只需更改一个位置,因为它已在其他任何地方使用,所以您就完成了。

更新

要绑定(bind) ng-click,我假设您有一个绑定(bind)到本地模型的输入,以及一个充当点击目标的按钮,如下所示:

<input type="text" data-ng-model="customerName" />
<button data-ng-click="lookupCustomer()">
Lookup Customer
</button>

然后在您的 Controller 中,您可以这样定义 lookupCustomer 函数:

app.controller('customersCtrl', [
'$scope', 'Customers',
function($scope, Customers) {
$scope.customerName = 'powercom';
$scope.lookupCustomer = lookupCustomer;
$scope.myData = null;

lookupCustomer();

function lookupCustomer() {
Customers.byName($scope.customerName)
.then(function(data) {
// Do something with data
});
}
}
]);

您可以在 lookupCustomer 内部添加检查以防止边缘情况(无需查找空客户名称),但这应该适合您。

关于javascript - AngularJS 中的规范化 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34856664/

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