答案 0 :(得分:1)
你需要的只是
<img ng-src="img/{{getImageIdOrName()}}.png">
您的代码没有多大意义,因为它只会在控制器实例化时初始化$scope.myImage
一次。每次选择更改时都需要获取一个新值,最简单的方法是从视图中调用该函数,如上所示。
另一种选择是在select上使用ng-change
,以便在每次选择更改时调用一个更改myImage
值的函数。
答案 1 :(得分:0)
您可以将ng-change事件绑定到选择框,并将值传递给控制器中的方法。
(function() {
app = angular.module('app', []);
app.controller("imgController", function($scope) {
function getImageIdOrName(param) {
var imageNames = ["earth", "moon", "sun"];
if (typeof param === "number") {
return imageNames[param - 1];
}
if (typeof param === "string") {
for (var i = 0; i <= imageNames.length; i++) {
if (imageNames[i] == param) {
return pad((i+1), 3);
}
}
}
}
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
//Function to be called whenever the values are changed in the select box
$scope.updateImage = function(){
$scope.myImage = "img/" + getImageIdOrName($scope.myImage) + ".png";
}
});
}());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="imgController">
<select ng-model="myImage" ng-change="updateImage(myImage)">
<option selected disabled>Make selection</option>
<option value="earth">Earth</option>
<option value="moon">Moon</option>
<option value="sun">Sun</option>
</select>
{{myImage}}
<img ng-src="{{myImage}}">
</div>
&#13;
答案 2 :(得分:0)
你可以这么做
<select ng-model="myImage">
<option selected disabled>Make selection</option>
<option value="earth">Earth</option>
<option value="moon">Moon</option>
<option value="sun">Sun</option>
</select>
{{myImage}}
<img ng-src="img/{{getImageIdOrName(myImage)}}.png">