当指令被渲染时,你的链接函数只被调用一次。
这意味着当您的 html 第一次呈现时,只有调用该函数。所以它完成了工作。当url发生变化时,需要监听器根据变化进行更新。
它不会与 URL 建立实时连接。
您需要在链接函数中为 $locationChangeSuccess 事件创建一个监听器。那应该做你的工作。
查看here 以获取文档。在那里搜索此功能。
然后,每当您更改 url 时,都会调用它并完成更改。你的指令变成这样:
myApp.directive('locationClass', function ($location, $rootScope) {
return {
restrict : 'A',
link: function (scope, element) {
$rootScope.$on('$locationChangeSuccess', function () {
var currentLocation = $location.path();
var formatCurrentLocation = currentLocation.replace(/\//g, " ");
//console.log(currentLocation);
element.addClass(formatCurrentLocation);
});
}
}
为了切换类而更新:
您使用范围变量代替。我们可以只用一个变量来存储类并将变量放在 html 上。检查 html 中的 locationClass 变量。
所以你的 html 会是这样的:
<html ng-app="myApp" ng-controller="headerCtrl as header" location-class class="{{locationClass}}">
和你的指令,我们修改为:
myApp.directive('locationClass', function ($location, $rootScope) {
return {
restrict : 'A',
link: function (scope, element) {
$rootScope.$on('$locationChangeSuccess', function () {
var currentLocation = $location.path();
var formatCurrentLocation = currentLocation.replace(/\//g, " ");
scope.locationClass = formatCurrentLocation;
});
}
}
所以现在每当你改变你的位置,当改变成功时,变量将在类属性上更新,你的 html 将有新的类。您无需手动删除旧类。
我认为这将解决问题,也是一种更好的做事方式。除非在 AngularJS 中必要,否则我们不想直接处理 DOM。如果变量可以做到这一点,我们就做到了。
更新 2:(如果您想使用手表):
我们可以监视 location.path() 并使用它来跟踪类名。
myApp.directive('locationClass', function ($location, $rootScope) {
return {
restrict : 'A',
link: function (scope, element) {
scope.$watch('$location.path()', function(currentLocation) {
var formatCurrentLocation = currentLocation.replace(/\//g, " ");
scope.locationClass = formatCurrentLocation;
});
}
}
但我仍然建议您寻找位置更改成功的监听器。
原因是手表很重,并且每次范围变脏时都会触发(如果范围在主体上,则意味着几乎每次),而事件侦听器仅在 url 更改时才会调用该函数。您可以在函数中放置一个控制台来检查和验证这一点。