Reputation: 85
I tried to use "ng-click" from angular into a html page and I managed. But if i try to use the same "ng-click" on the same function in a bootstrap modal code don't work anymore. Why. How to call mehod in the second case ?
This is my html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-controller="MainController">
<a href="" ng-click="first()">Call from file</a><br/>
<a href="#about" data-toggle="modal">Call from a pop-up</a>
</div>
<div class="modal fade" id="about" role="dialog">
<div class="modal-dialog" modal-sm>
<div class="modal-content">
<div class="modal-header">
<h4>Pop-up head.</h4>
</div>
<div class="modal-body">
<h4>Pop-up body.</h4>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="first()">Send</button>
</div>
</div>
</div>
</div>
</body>
</html>
And this is my script
var myApp = angular.module('myApp', []);
myApp.controller("MainController", function($scope){
$scope.val= 1
$scope.even= false
$scope.increment = function(){
$scope.val +=1
$scope.even = ($scope.val%2 == 0)?true:false;
//$scope.even = $scope.val%2 == 0
}
$scope.first = function(){
alert("work");
}
})
Upvotes: 4
Views: 9352
Reputation: 12184
The reason is that when the modal shows up the processing of all angular directives is already over. Hence the ng-click attribute on the template of modal that is going to be appended to the DOM later on makes no difference.
Generally you would like the HTML to be compiled with a the correct scope.
If you don't want to get into details of this, use Angular UI for Bootstrap This will give you nice directives and services for bootstrap widgets.
There is a $modal service that can be used just like the $http service which returns a promise. Here also you can have callbacks for events when modal disappears or closes.
There is sample code in the example. Here is how a function that will bring up a modal would look like:
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
Upvotes: 4