控制器 div 中的 $scope 在路由更改后未更新

$scope in controller div not updating after routing change

我有 ng-view partials,它根据 $routeProvider 中的路由更改进行更新。

anmSite.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode(true);

$routeProvider
    //Route for home page
    .when("/", {
        templateUrl: "templates/main.html",
        controller: "imageController",
        title: "Passionate about perfection",
    })
    //Route for about page
    .when("/me", {
        templateUrl: "templates/me.html",
        controller: "imageController",
        title: "About Me",
    })
    //Route for design page
    .when("/design", {
        templateUrl: "templates/design.html",
        controller: "imageController",
        title: "Site Design",
    })
    //Route for projects page
    .when("/projects", {
        templateUrl: "templates/projects.html",
        controller: "imageController",
        title: "Projects",
    })
    //Route for photos page
    .when("/photos", {
        templateUrl: "templates/photos.html",
        controller: "imageController",
        title: "Photos",
    })
    //Default route to /
    .otherwise({
        redirectTo: "/"
    });
});

所有路由调用相同的 'imageController',它根据 $location.path().

更新 $scope
anmSite.controller("imageController", function($scope, $location){

var image = {
    class: "",
    text: ""
};

var imageClass, imageText = "";
switch($location.path()){
    case "/me":
        image.class = "me";
        image.text = "Me";
        break;
    case "/design":
        image.class = "design";
        image.text = "Design";
        break;
    case "/projects":
        image.class = "projects";
        image.text = "Projects";
        break;
    case "/photos":
        image.class = "photos";
        image.text = "Photos";
        break;
    default:
        image.class = "surfer";
        image.text = "Surfer";
        break;
}
$scope.image = {
    class: image.class,
    text: image.text
};

});

我在 index.html 中的部分上方放置了一个,这对于所有具有 2 个需要为每个路由更新的 $scope 变量的页面都是通用的。

<div ng-controller="imageController">
    <div class="image-container {{ image.class }}">
        <h1>{{ image.text }}</h1>
    </div>
</div>

<div class="ng-view"></div>

这在页面首次加载时有效,但 ng-controller div 不会针对每次路由更改进行更新,即使 $scope 变量已更新(使用 console.log 检查)。是否可以更新 ng-controller 视图?我需要使用其他指令吗?如果有任何建议,我将不胜感激。

请尝试在 "ng-view" 之间移动您的代码。 根据 angular 文档

ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.

类似于

<div class="ng-view">

<div ng-controller="imageController">
<div class="image-container {{ image.class }}">
    <h1>{{ image.text }}</h1>
</div>
</div>
</div>

编辑 - 根据下面的对话评论,有效的方法是有一个指令,并且在 link 函数内部它将跟踪 $routechangevents ,例如 $routechangestart ,它将 运行 每次路由更改并且每次都会更新您的范围

希望这对您有所帮助,

快乐学习