Trax Trax - 5 months ago 45
AngularJS Question

Angular on button click outside ctrl, pass button id

I want to call a function from outside the controller and pass it the button id. This is my current code :

<button class="btn btn-primary manageCompany" id=<%=comp._id%> data-toggle="modal" data-target="#manageCompany_pp" ng-click="clickMe()">Manage</button>
// .. More code


<div class="modal fade" ng-controller="ModalCtrl" id="manageCompany_pp" tabindex="-1" cid="" role="dialog" aria-labelledby="manageCompany_pp">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title" id="manageCompany_content">Manage Company</h4>
</div>
<div class="modal-body">
<div class='manageCompanyAlert'></div>
{{testData}}
<script> </script>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>


And this is the content of my controller

app.controller('ModalCtrl', ['$scope', '$http', function($scope, $http) {
$scope.clickMe = function() {
$http.post('/modalRoutes/cdata', {
id: 0 // Button ID should go here
}).success(function(cdata) {
$scope.testData = cdata;
});
};
}]);


EDIT:
For now it seems that the best way was just to create a main controller for the whole page and handle it from there.

Answer

You should be able to pass the id into the function directly:

ng-click="clickMe(<%=comp._id%>)"

And:

app.controller('ModalCtrl', ['$scope', '$http', function($scope, $http) {
    $scope.clickMe = function(id) {
        $http.post('/modalRoutes/cdata', {
            id: id
        }).success(function(cdata) {
            $scope.testData = cdata;
        });
    };
}]);
Comments