Rabbi Shuki Rabbi Shuki - 3 months ago 14
AngularJS Question

ng-click and ng-href on the same element

I have a list that I am populating via ng-repeat of links.

some of these links need to open as links via ui-router, and some need to open as modals via ui-bootstrap.

This is my Html

<div class="sub-menu">
<li ng-repeat="sub in menu track by $index">
<a ng-controller="ModalController" ng-click="open(sub.click)" ng-href="#/{{sub.link}}">
<i class="fa {{sub.icon}}"></i> {{sub.name}} </a>
</li>
</div>


and the data looks like this:

$scope.menu = [{
icon: 'fa-plus-square',
name: 'new',
click: 'newModal'
}, {
icon: 'fa-th-list',
name: 'list',
link: 'ui_bootstrap.html'
}


The problem is, that all links are sent to the ModalController, thus the first link opens a modal, but the second one doesn't reload the page.

I tried adding an if to the ModalController as so:

$scope.open = function (link) {
if (link) {
var out = $uibModal.open({
templateUrl: "views/modals/" + link + ".html",
controller: "ModalInstanceController",
resolve: {
items: function () {
return $scope.items;
}
}
});
out.result.then(function (value) {
$scope.selected = value;
}, function () {
$log.info("Modal dismissed at: " + new Date);
});
};
}


But that still isn't fixing the problem.

Any solution? or better way to do this?

Answer

You can use click only. And in the controller on click, you can check if there is a link then you can use routing else you can open a pop-up.

<a ng-controller="ModalController" ng-click="open(sub)">

Controller

$scope.open = function (sub) {
    if (sub.click) {
      var out = $uibModal.open({
        templateUrl: "views/modals/" + sub.click + ".html",
        controller: "ModalInstanceController",
        resolve: {
          items: function () {
            return $scope.items;
          }
        }
      });
      out.result.then(function (value) {
        $scope.selected = value;
      }, function () {
        $log.info("Modal dismissed at: " + new Date);
      });
    } else {
      $state.transitionTo(sub.link);
    };
  }
Comments