Как установить положение элементов сверху и слева в директиве ng-repeat после обновления угловой модели - PullRequest
0 голосов
/ 03 апреля 2019

Я генерирую кучу тегов через angularjs ng-repeat, их нужно расположить по кругу, манипулируя их верхними и левыми настройками стиля.

Это то, что у меня есть,который корректно позиционирует их при загрузке страницы, но при обновлении модели теряет позиционирование:

Кто-то предложил сделать это в ng-repeat directive, но я не уверен, как, как я могу это сделатьвыполнить это?

<script type="text/javascript" id="ModuleMenuModalInit">
    window.objectModel = @Html.Raw(Model);
</script>
<script type="text/javascript" src="@Url.Content("~/Scripts/AngularControllers/_ModuleLauncherController.js")"></script>
<div id="nukeModules" class="launcherDiv" ng-controller="ModuleLauncherController as mmvm" ng-init="mmvm.initializeController()">
    <div id="divCircle" style="background-color:pink;">
        <div id="middleBubble">
            <img class="iconLarge" />
            <p id="bubbleText">&nbsp;</p>
        </div>
        <a ng-repeat="module in mmvm.moduleMenus"
           id="lb_{{module.Prefix}}"
           data-primary="{{module.Name}}"
           data-secondary="{{module.Description}}"
           access-text="" module="{{module.Prefix}}"
           ng-class="{
                    launcherbutton: true,
                    not_active: module.AssociatedUserModule == null || (module.AssociatedUserModule != null && !module.AssociatedUserModule.Accessible)
                   }">
            <img alt="{{module.Prefix}}" src="{{module.ImagePath}}">
        </a>
    </div>
</div>

угловой контроллер:

var NucleiApp = angular.module('NucleiApp');
NucleiApp.controller('ModuleLauncherController', ['$scope', '$http', '$location', function ($scope, $http, $location) {

    var mmvm = this;

    mmvm.initializeController = function () {
        mmvm.moduleMenus = window.objectModel.modules;
        delete window.moduleMenuModel;
        RemoveModuleMenuModalInitScript();
    }

    function ReloadModuleMenus() {
        $http({
            method: 'GET',
            url: uriPrefix + '/ModuleMenu/RefreshModules'
        }).then(function (response) {
            mmvm.moduleMenus = response.data.moduleMenus;
            positionLauncherButtons();
        }, function (error) {
            alert("Unexpected error in _ModuleMenuController.js controller vm.LoadData");
            console.log(error, 'can not get data.');
        });
    }

    angular.element(document).ready(function () {
        positionLauncherButtons();
    });

    mmvm.refreshModuleMenus = function (displayMenu) {
        ReloadModuleMenus();
    }
}]);
function positionLauncherButtons() {
    //Arrange the icons in a circle centered in the div
    numItems = $("#divCircle a").length; //How many items are in the circle?
    start = 3.927; //the angle to put the first image at. a number between 0 and 2pi
    step = (2 * Math.PI) / numItems; //calculate the amount of space to put between the items.
    $("#divCircle a").each(function (index) {
        radius = ($("#divCircle").width() - $(this).width()) / 2;
        tmpTop = (($("#divCircle").height() / 2) + radius * Math.sin(start)) - ($(this).outerHeight() / 2);
        tmpLeft = (($("#divCircle").width() / 2) + radius * Math.cos(start)) - ($(this).outerWidth() / 2);
        start += step; 

        $(this).css("top", tmpTop);
        $(this).css("left", tmpLeft);
    });
}

1 Ответ

1 голос
/ 03 апреля 2019

Поместите функцию позиционирования в $ applyAsync :

function ReloadModuleMenus() {
    $http({
        method: 'GET',
        url: uriPrefix + '/ModuleMenu/RefreshModules'
    }).then(function (response) {
        mmvm.moduleMenus = response.data.moduleMenus;
        $scope.$applyAsync(function() {
          positionLauncherButtons();
        });
    }, function (error) {
        alert("Unexpected error in _ModuleMenuController.js controller vm.LoadData");
        console.log(error, 'can not get data.');
    });

Это даст директиве ng-repeat время для добавления новых элементов в DOM.

...