SolarTerms.controller('FooterCtrl', ['$state', '$rootScope', '$scope', function ($state, $rootScope, $scope) {
$scope.imgsrc = {
"imda1":"img/icon1.png",
"imda2":"img/icon2.png",
"imda3":"img/icon3.png",
"imda4":"img/icon4.png",
"imda5":"img/icon5.png"
}
}])
SolarTerms.directive("tabImg",function () {
return {
restrict:'A',
scope:false,
link:function (scope,ele,attr,ctrl) {
ele.bind('click',function (event) {
var index = $(this).index();
scope.imgsrc = {
"imda1":"img/icon1.png",
"imda2":"img/icon2.png",
"imda3":"img/icon3.png",
"imda4":"img/icon4.png",
"imda5":"img/icon5.png"
};
scope.imgsrc['imda'+(index+1)] = 'img/icon'+(index+1)+'1.png';
//scope.$apply(scope.imgsrc['imda'+(index+1)] = 'img/icon'+(index+1)+'1.png')
})
}
}
})
<p tab-img class="I_AF_p" ng-click="goto('index')"><img ng-src="{{imgsrc.imda1}}" alt=""> <span>首頁</span></p>
<p tab-img class="I_AF_p" ng-click="goto('ye')"><img ng-src= "{{imgsrc.imda2}}" alt=""><span>餘額</span></p>
<p tab-img class="I_AF_p" ng-click="goto ('js')"><img ng-src="{{imgsrc.imda3}}" alt=""><span>計算</span></p>
< p tab-img class="I_AF_p" ng-click="goto('ck')"><img ng-src="{{imgsrc.imda4}}" alt=""><span>查看</span></p>
<p tab-img class="I_AF_p" ng-click="goto('wd')"><img ng-src="{{imgsrc. imda5}}" alt=""><span>文檔</span></p>
點擊對應的p之後取得索引,然後更改$scope.imgsrc中對應的值,控制台能正確輸出圖片位址,但是視圖中ng-src中的值為什麼需要點擊兩次才能改變,我只是想更改ng-src中的圖片地址,剛開始學angularjs,誰幫我解釋下,謝謝。
PHP中文网2017-05-16 13:20:53
需要手動觸發angular的渲染機制
link:function (scope,ele,attr,ctrl, $timeout) {
ele.bind('click',function (event) {
var index = $(this).index();
scope.imgsrc = {
"imda1":"img/icon1.png",
"imda2":"img/icon2.png",
"imda3":"img/icon3.png",
"imda4":"img/icon4.png",
"imda5":"img/icon5.png"
};
$timeout(function() {
scope.imgsrc['imda'+(index+1)] = 'img/icon'+(index+1)+'1.png';
//scope.$apply(scope.imgsrc['imda'+(index+1)] = 'img/icon'+(index+1)+'1.png')
})
})
}