Patrick Pirzer Patrick Pirzer - 11 days ago 8
Javascript Question

Why is $scope.modal undefined when i try to open an ionic template modal?

I'm working on an Ionic-app for iPad.
In one of my templates i have a treeview with items.
When i click on items i want to open other templates modal.
I tried it with one of my templates but i get an error, that $scope.modal in the controller is undefined.

Further, can the loaded template use it's own controller?

This is my controller-code:

.controller('SystemValidateCtrl', function ($scope, $state, $stateParams, $ionicModal, ComponentTree, TypeOfTests, TypeOfTestReasons) {
$scope.showTypeOfTest = function () {
$ionicModal.fromTemplateUrl('templates/type-of-test.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function (modal) {
$scope.modal = modal;
});
};
$scope.openModal = function () {
$scope.modal.show();
};
$scope.closeModal = function () {
$scope.modal.hide();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function () {
$scope.modal.remove();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function () {
// Execute action
});
// Execute action on remove modal
$scope.$on('modal.removed', function () {
// Execute action
});

$scope.$on('$ionTreeList:ItemClicked', function (event, item) {
//TODO: Show the template according to the item.id
var panel_dynamic = document.getElementById('panel_dynamic_to_treeitem');
if (panel_dynamic.hasChildNodes()) {
panel_dynamic.removeChild(panel_dynamic.childNodes[0]);
}
var line = document.createElement("div");

if(item.id == 9999) //Anzeige der Testarten
{
$scope.showTypeOfTest();
$scope.openModal();
}
})
})

Answer

Since fromTemplateUrl returns a promise,

$scope.showTypeOfTest();
$scope.openModal();

will not work because modal is not defined due to $scope.modal = modal;was not called yet.

suggestion: refactor to chaining promise :

showTypeOfTest = function() {
 return $ionicModal.fromTemplateUrl('templates/type-of-test.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.modal = modal;
        });
}

then you can use

$scope.showTypeOfTest().then($scope.openModal);
Comments