jQuery MixItUp с AngularJS NgRoute

Мне удалось интегрировать jQuery MixItUp в мое приложение AngularJs.

Элементы, которые должны отображаться с помощью MixItUp, загружаются из пользовательских служб. Как только все элементы будут получены, я запускаю создание экземпляра jQuery MixItUp.

Я также использую AngularJS NgRoute для реализации разных страниц.
Когда я впервые захожу на страницу, где используется jQuery MixItUp, все в порядке. Но когда я перехожу на другую страницу и возвращаюсь на страницу с jQuery MixItUp, фильтры и сортировка больше не работают.

Я настраиваю свои маршруты следующим образом:

myApp
.config(function($routeProvider, $locationProvider) {
    $routeProvider

        // some routes for other pages
        .when('/', {
            templateUrl : '/assets/js/app/views/home.html',
            controller  : 'MainController'
        })
        .when('/about', {
            templateUrl : '/assets/js/app/views/about.html',
            controller  : 'AboutController'
        })

        // route for page where MixItUp is used
        .when('/media', {
            templateUrl : '/assets/js/app/views/media.html',
            controller  : 'MediaController'
        })

        // 404
        .otherwise({
            redirectTo  : '/404'
        })

    $locationProvider.html5Mode(true);
});

В моей пользовательской директиве я запускаю jQuery MixItUp с некоторыми параметрами и исправляю сортировку после инициализации. console.log регистрируются в консоли каждый раз, когда я посещаю или повторно посещаю страницу. Но при повторном посещении нарушается функциональность фильтров и сортировки. Пользовательская директива выглядит так:

myApp
.directive('mixitup', function($compile) {

    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            scope.$on('init-mixitup', function(event) {
                console.log('[event] înit-mixitup');
                angular.element(element).mixItUp({
                    animation: {
                        duration: 200
                    },
                    load: {
                        sort: 'myorder:desc'
                    },
                    debug: {
                        enable: true,
                        mode: 'normal'
                    }
                });
            });

            scope.$on('resort-mixitup', function(event, sortCommand) {
                console.log('[event] resort-mixitup');
                angular.element(element).mixItUp('sort', sortCommand);
            });
        }
    };
});

В моем контроллере AngularJS (MediaController) я транслирую события после того, как все элементы будут получены из пользовательских служб:

// init
$rootScope.$broadcast('init-mixitup');

// sort
$rootScope.$broadcast('resort-mixitup', 'myorder:desc');

HTML-код представления выглядит следующим образом:

<div class="btn-group controls">
    <button class="btn btn-lg filter"
        data-filter="all">All</button>
    <button class="btn btn-lg filter"
        data-filter=".photo">Photo</button>
    <button class="btn btn-lg filter"
        data-filter=".audio">Audio</button>
    <button class="btn btn-lg filter"
        data-filter=".video">Video</button>
</div>

<div mixItUp="mixItUp" id="mixitup-container">
    <div ng-repeat="item in items"
        id="{{ item.id }}"
        style="display: inline-block;"
        data-myorder="{{ item.date }}"
        class="mix col-xs-6 col-sm-4 {{ item.category }}">
            <img ng-src="{{ item.image }}" class="img-responsive img-circle">
    </div>
</div>

Консоль Javascript в chrome выводит следующее при загрузке первой страницы:

[event] înit-mixitup
[MixItUp][mixitup-container][_bindHandlers] 4 filter buttons found.
[MixItUp][mixitup-container][_init] MixItUp instantiated on container with ID "mixitup-container".
[MixItUp][mixitup-container][_init] There are currently 1 instances of MixItUp in the document.
[event] resort-mixitup
[MixItUp][mixitup-container][multiMix] Operation requested via the API.
[MixItUp][mixitup-container][multiMix] An operation was requested but MixItUp was busy. The operation was added to the queue in position 1.
[MixItUp][mixitup-container][multiMix] Loading operation from queue. There are 0 operations left in the queue.
[MixItUp][mixitup-container][multiMix] Operation requested via the API.
[MixItUp][mixitup-container][multiMix] Operation started.
[MixItUp][mixitup-container][_cleanUp] Loading animation completed successfully.
[MixItUp][mixitup-container][_cleanUp] The operation completed successfully.

И при загрузке второй страницы (после перехода на другие страницы, без перезагрузки браузера):

[event] înit-mixitup
[event] resort-mixitup
[MixItUp][mixitup-container][multiMix] Operation requested via the API.
[MixItUp][mixitup-container][multiMix] Operation started.

Здесь есть еще один вопрос, связанный с этой проблемой: Как инициировать MixItUp с помощью AngularJS NgRoute Но там элементы не загружаются динамически через пользовательские сервисы.


person freakimkaefig    schedule 11.11.2015    source источник


Ответы (2)


Я исправил проблему, вызвав функцию jQuery MixItUp destroy при выходе со страницы.

Я добавил еще один прослушиватель событий в свою директиву для MixItUp:

myApp
.directive('mixitup', function($compile) {

    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            scope.$on('init-mixitup', function(event) {
                // console.log('[event] înit-mixitup');
                angular.element(element).mixItUp({
                    animation: {
                        duration: 200
                    },
                    load: {
                        sort: 'myorder:desc'
                    }
                });
            });

            scope.$on('resort-mixitup', function(event, sortCommand) {
                // console.log('[event] resort-mixitup');
                angular.element(element).mixItUp('sort', sortCommand);
            });

            scope.$on('destroy-mixitup', function(event) {
                // console.log('[event] destroy-mixitup');
                angular.element(element).mixItUp('destroy');
            })
        }
    };
});

А также добавил триггер события в моем контроллере AngularJS (MediaController):

$scope.$on("$destroy", function(){
    $rootScope.$broadcast('destroy-mixitup');
});
person freakimkaefig    schedule 11.11.2015

Что насчет этого !!!

    'use strict';
  angular.module('rjApp')
    .directive('mixitup',function($timeout,$compile){
      var linker = function(scope,element,attr) {

        scope.$watch('entities', function(newVal, oldVal){

            if (element.mixItUp('isLoaded')) {
              element.mixItUp('destroy');
              element.mixItUp();
            } else {
              element.mixItUp();
            }
        },true);

      };
      return {
        link: linker,
        scope:{entities:'='}
      }
    })
person Sanjit Bauli    schedule 04.04.2016