ng-include 中的指令仅在第一次运行

a directive inside an ng-include works only for the first time

我有一个带有左侧菜单的页面。单击锚标记后,我会在页面中的 div 上加载部分视图。所有菜单项都要求 uires 具有不同数据的相同 ng-template。

我在做什么:

ParentPage.cshtml

<div id="sub_menu">
    <ul>
        <li><a href="" target="_parent" ng-click="Navigate('gallery')"><div>Gallery</div></a></li>
        <li><a href="" target="_parent" ng-click="Navigate('corporate')"><div>Corporate Images</div></a></li>
        <li><a href="" target="_parent" ng-click="Navigate('icons')"><div>Icons</div></a></li>
    </ul>
</div>
<div ng-if="Obj.showDiv == 'galleries'" ng-include="'Galleries/galleries'">
</div>

Angular 控制器:

var app = angular.module('home', []);

app.controller('homeCtrl', ['$scope', '$http', '$window', function ($scope, $http, $window, $templateCache) {
    $scope.Navigate = function (viewType) {
        $scope.Obj.showDiv = "galleries";
        $scope.Obj.gallery = $scope.baseGallerypath.concat(viewType).concat('/');
        $scope.$digest();
    }
}]);

galleries.cshtml(儿童 page/partial 视图)

<div class="photos">
    <ul image-gallery gallery="Obj.gallery">
    </ul>
</div>

imagegallery.js(我的指令):

var App = angular.module('app');

App.directive('imageGallery', function ($http, $compile, $timeout) {
    return {
        // Restrict it to be an attribute in this case
        restrict: 'A',
        replace: true,
        scope: true,
        // responsible for registering DOM listeners as well as updating the DOM
        controller: function ($scope, $element, $attrs) {
            $scope.galleryPath = $scope.$eval($attrs.gallery);  
            //my logic to render the image gallery is here
        }
    };
});

我的问题:

当我单击 link 时,将调用指令并呈现 ui。但是当我点击任何其他 link(菜单项)时,我的指令没有被执行。我在控制台上没有看到任何错误。

我们有办法强制 ng-include 每次都加载指令吗? 不确定它是否被缓存。

问题出在指令上。 指令第一次启动时,值已经存在,所以它会呈现你想做的任何事情。在随后的点击中,ng-if 和 ng-include 没有改变,所以指令没有被第二次初始化,值也没有更新。 ng-include 和 ng-if 是多余的。更改值应该在 $scope.$watch 函数中处理,然后 angular 将对更改做出反应。

顺便说一句 - 你不需要 $scope.$digest(),因为当你点击 ng-click 时你已经有了一个 $digest 循环。

<div id="sub_menu">
    <ul>
        <li><a href="" target="_parent" ng-click="Navigate('gallery')"><div>Gallery</div></a></li>
        <li><a href="" target="_parent" ng-click="Navigate('corporate')"><div>Corporate Images</div></a></li>
        <li><a href="" target="_parent" ng-click="Navigate('icons')"><div>Icons</div></a></li>
    </ul>
</div>

<div class="photos">
    <ul image-gallery gallery="Obj.gallery">
    </ul>
</div>

JS:

App.directive('imageGallery', function ($http, $compile, $timeout) {
    return {
        // Restrict it to be an attribute in this case
        restrict: 'A',
        replace: true,
        scope: {
        gallery: "="
    },

    // responsible for registering DOM listeners as well as updating the DOM
    controller: function ($scope, $element, $attrs) {
        $scope.$watch("gallery", function(gallery) {
            // make all changes inside the $watch function body using gallery as the value
        });
    }
};