ng-include中的指令仅适用于第一次

时间:2015-07-27 20:18:58

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-include

我有一个左侧菜单的页面。在单击锚标签时,我在页面中的div上加载局部视图。所有菜单项都需要相同的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>

角度控制器:

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(子页/部分视图)

<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
        }
    };
});

我的问题:

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

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

1 个答案:

答案 0 :(得分:0)

问题在于指令。 指令第一次上升时,该值已经存在,因此它会呈现您想要做的任何事情。在随后单击时,ng-if和ng-include不会更改,因此指令不会再次初始化,并且不会更新该值。 ng-include和ng-if是多余的。更改值应在$ scope。$ watch函数内处理,然后angular将对更改做出反应。

btw - 您不需要$scope.$digest(),因为当您点击ng-click时已有$摘要周期。

<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
        });
    }
};