Angularjs ng-controller with resolve

前端 未结 8 531
时光取名叫无心
时光取名叫无心 2021-02-01 20:30

I\'ve ran into problem with ng-controller and \'resolve\' functionality:

I have a controller that requires some dependency to be resolved before running, it works fine w

8条回答
  •  迷失自我
    2021-02-01 21:30

    You can use the mechanism of the prototype.

    .when('/someUrl', {
        template : '
    ', controller: function (data) { var pr = this; pr.data = data; }, controllerAs: 'pr', resolve : { data: ['Service', function (Service) { return Service.getData(); }] } }) angular.module('myApp') .controller('MyController', ['$scope', function ($scope) { $scope.data = $scope.pr.data; //magic } ] );

    Now wherever you want to use

    '
    '

    you need to ensure that there pr.data in the Scope of the calling controller. As an example uib-modal

    var modalInstance = $modal.open({
        animation: true,
        templateUrl: 'modal.html',
        resolve: {
            data: ['Service', function (Service) {
                return Service.getData();
            }]
        },
        controller: function ($scope, $modalInstance, data) { 
            var pr = this;
            pr.data = data;
            pr.ok = function () {
                $modalInstance.close();
            };
        },
        controllerAs:'pr',
        size:'sm'
    });
    

    modal.html

    
    

    And now you can use $scope.data = $scope.pr.data; in MyController

    pr.data is my style. You can rewrite the code without PR. the basic principle of working with ng-controller described in this video https://egghead.io/lessons/angularjs-the-dot

提交回复
热议问题