[英]calling javascript function in controller from ionic template
创建我的第一个Ionic应用程序,到目前为止进展顺利。 我不是UI使用者,所以我确定我不会以最佳风格做事,但是无论如何...
我有一个模板,其中包含此代码。 (我拿出了多余的东西,并试图将其简化为问题的症结所在,因此请忽略任何语法错误。)
<ion-content class="padding">
<div ng-repeat="entry in entries">
<div class="list card item-remove-animate">
<a class="item item-divider">{{entry.name}}</a>
<a class="item item-body">
<b>Type:</b> {{entry.typeCode}}
</a>
</div>
</div>
</ion-content>
当前显示的entry.typeCode是每个条目中存储的内容,但我确实想显示该代码所引用的类型字符串。 我的控制器中有一个函数,可以执行从typeCode到typeString的映射,但是我不知道如何调用它。
var typeCodeMappings = {
"B" : "Bike",
"A" : "Auto",
"T" : "Train",
"P" : "Plane"
};
app.controller('EntriesCtrl', function($scope, $http) {
$scope.typeCodeToString = function(code) {
return typeCodeMappings[code];
}
$http.get("...queryUrl...").then(
function(response) {
$scope.entries = response.data.results;
},
function(reason) {
console.log("Failed reading entries, reason=" + reason);
}
);
}
在《 Ionic用户指南》中浏览了所有内容,或者我错过了它,或者我做错了,并且错过了范例。 我知道我可以在ng-Click =“ myFunction()”等指令中调用绑定到$ scope的JS函数,但是仅在显示内容时该怎么做? 我只想从模板调用typeCodeToString(entry.typeCode)。
请注意,我不仅需要在控制器中调用该函数,而且还要为正在模板中迭代的“条目”传递typeCode。
我不知道您的typeCodeMappings如何返回字符串。 但是,在控制器本身内定义功能可以实现您所要求的。 因为,您不想从DOM而是在控制器内调用函数。
app.controller('EntriesCtrl', function($scope, $http) {
function typeCodeMappings(code){
var string;
if(code == "B"){
string = "Bike";
return string;
}
if(code == "A"){
string = "Auto";
return string;
}
if(code == "T"){
string = "Train";
return string;
}
if(code == "P"){
string = "Plane";
return string;
}
}
$http.get("...queryUrl...").then(
function(response) {
$scope.entries = response.data.results;
//i dont know your entries structure but loop the conversion
angular.forEach($scope.entries, function(value, key) {
value.typeCode = typeCodeMappings(value.typeCode);});
},
function(reason) {
console.log("Failed reading entries, reason=" + reason);
}
);
}
您可以在$ scope上指定您的typecodeMappings,如下所示。
$scope.typeCodeMappings = {
"B" : "Bike",
"A" : "Auto",
"T" : "Train",
"P" : "Plane"
};
在html视图中
{{entry.typeCode}}-{{typeCodeMappings [entry.typeCode]}}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.