Search code examples
angularjsangular-bootstrap

How can I not use $scope in an AngularJS Bootstrap modal?


I have this code inside a controller. I'm using it to open an angularJS Bootstrap modal with another controller attached.

Is there a way I can not use $scope for the ok() and cancel() functions here?

   $scope.deleteTest = (test: ITest) => {
        var self = this;
        var modalInstance = $modal.open({
            templateUrl: '/app/tests/partials/deleteTest.html',
            controller: ['$scope', '$modalInstance', 'testService',
                function ($scope, $modalInstance, testService: ITestService) {
                    $scope.ok = () => {
                        var self = this;
                        testService.deleteTest()
                            .then(
                                () => {
                                    $modalInstance.close();
                                });
                    };
                    $scope.cancel = () => {
                        $modalInstance.dismiss('cancel');
                    };
                }],
        });
    }

Solution

  • Looks like you are using TypeScript so you can do something like this

    var modalInstance = $modal.open({
        templateUrl: '/app/tests/partials/deleteTest.html',
        controller: DeleteTest,
        controllerAs: 'ctrl'
    });
    
    //...
    
    class DeleteTest {
        static $inject = ['$modalInstance', 'testService'];
    
        constructor(private $modalInstance, private testService: ITestService) {
    
        }
    
        ok() {
            this.testService.deleteTest().then(() => this.$modalInstance.close());
        }
    
        cancel() {
            this.$modalInstance.dismiss('cancel');
        }
    
    }
    

    In deleteTest.html you could call the ok() method with something like

    <button ng-click="ctrl.ok()">Ok</button>