gpt4 book ai didi

javascript - Angular,使用服务显示数组

转载 作者:行者123 更新时间:2023-12-02 13:55:02 25 4
gpt4 key购买 nike

我正在通过做小练习来学习 Angular 。我已成功在 Controller 中显示对象并尝试学习使用服务和工厂。我无法使用服务在表上显示数组“名称”。请查看我的代码,看看我做错了什么,以及如何使用工厂来显示相同​​的数组。这是我的代码

收到部分答案后编辑的问题:

工厂并非不显示种族信息。

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

myApp.filter("agefilter", function(){

var x= function(age){
if(age==23||age==22){

return "Young";
}

if(age==25){

return "Mature";
}
if(age==26){

return "Oldest";
}
}
return x;
});





myApp.controller("ctrl", function($scope,factoryy){

$scope.person=[

{name:"jay",age:25,salary:85000},
{name:"anu",age:23,salary:65000},
{name:"jose",age:26,salary:75000},
{name:"sharon",age:22,salary:70000}


];

// $scope.callnames = servicee.names();
$scope.calleth = factoryy.geteth();


});



myApp.factory("factoryy",function(){

var ethnicity = ["Asian-Indian","Asian-Indian","Chinese","Latino","American"];

return{

geteth: function(){

return ethnicity;
}
}

});


// myApp.service("servicee",function(){

// var names= ["jay","anu","sharon","jose","mary"];
// this.names = function(){
// return names;
// }


// });
 <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<title></title>
</head>
<body ng-app="app" ng-controller="ctrl" >


<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Salary</th>


</tr>

<tr ng-repeat="i in person">
<td>{{i.name |uppercase }}</td>
<td>{{i.age|agefilter}}</td>
<td>{{i.salary|currency}}</td>


</tr>



</table><br><br><br>


<!--<table border="1">
<tr><th>Name</th></tr>

<tr ng-repeat="s in callnames">

<td>{{s}}</td>
</tr>

</table>-->



<table border="1">
<tr>

<th>Ethnicity</th>

</tr>

<tr ng-repeat="e in calleth">

<td>{{e}}</td>
</tr>

</table>



<script src="../js/angu.js"></script>
</body>
</html>

最佳答案

因此,为了修复当前的实现,您只需要做两件事,首先将 Controller 中的 servicee.names 更新为 servicee.names() 并然后在模板中将 s.names 更新为 s

为了对工厂执行相同的功能,您可以这样做:

myApp.factory("nameFactory",function(){
var names= ["jay","anu","sharon","jose","mary"];

return {
getNames: function(){
return names;
}
}
});
myApp.controller("ctrl", function($scope,nameFactory){
$scope.person=[
{name:"jay",age:25,salary:85000},
{name:"anu",age:23,salary:65000},
{name:"jose",age:26,salary:75000},
];

$scope.callnames = nameFactory.getNames();
});

工厂和服务之间的区别在于,工厂只是一个返回的函数,因此我们可以返回一个公开我们想要的任何值或函数的对象,而服务则使用 new< 进行初始化 运算符允许我们通过将任何内容附加到 this

来简单地公开任何内容

关于javascript - Angular,使用服务显示数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40755329/

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