在 AngularJS 中更改路由上的图标图像

Changing the icon image on routing in AngularJS

本文关键字:图标 图像 路由 AngularJS      更新时间:2023-09-26

我想在转到/tab1 后更改图像。这可以通过"ng-click"来完成。但是需要使用AngularJS路由来完成。

网页文件:

<div class = "body" ng-controller = "app">
    <div class = "column1">
        <div class = "tab1">
            <a href = "#/tab1"><img ng-src="{{ imageUrl }}"></a>
        </div>

控制器.js :

var application = angular.module('mainApp', ['ngRoute']);
application.controller('app', function($scope) {
    console.log("Executed");
    $scope.imageUrl = 'profile-icon.png';
});
application.config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/tab1', {templateUrl: 'tab1.html', controller: HomeCtrl}).
            when('/tab2', {templateUrl: 'tab2.html'}).
            when('/tab3', {templateUrl: 'tab3.html'}).
            otherwise({redirectTo: '/'});
}]);
function HomeCtrl($scope) {
    console.log("Inside ToggleImage");
    $scope.imageUrl = 'profile-icon-clicked.png';
}

页面成功加载"个人资料图标.png"。但是点击后图像没有变化。但我可以在浏览器控制台中看到输出"内部切换图像"。

这是怎么回事?

imageUrl

两个控制器中处于不同的范围内。如果您希望它们在任何地方都相同,请使用$rootscope而不是$scope

这是因为您修改了子作用域的属性,而不是父作用域的属性。有关作用域继承的说明,请参阅 https://github.com/angular/angular.js/wiki/Understanding-Scopes。

解决此问题的最简单方法是在父作用域上拥有一个对象。

var application = angular.module('mainApp', ['ngRoute']);
application.controller('app', function($scope) {
    console.log("Executed");
    $scope.settings= {imageUrl: 'profile-icon.png'};
});
application.config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/tab1', {templateUrl: 'tab1.html', controller: HomeCtrl}).
            when('/tab2', {templateUrl: 'tab2.html'}).
            when('/tab3', {templateUrl: 'tab3.html'}).
            otherwise({redirectTo: '/'});
}]);
function HomeCtrl($scope) {
    console.log("Inside ToggleImage");
    $scope.settings.imageUrl = 'profile-icon-clicked.png';
}