Elliot
Elliot

Reputation: 13845

problems with ng-click and ng-show

I'm trying to make a little modal framework in my app..

Heres my controller:

function ModalCtrl($scope){
    $scope.openModal = function(name){
        $scope.modalStatus = true;
    }
    $scope.closeModal = function(name){
        $scope.modalStatus = false;
    }
    $scope.modal = function(){
        return $scope.modalStatus;
    }
    $scope.modalStatus = false;
}

And heres the HTML:

<div ng-controller="ModalCtrl">
  <div ng-show="modal()" class="modal_window">
    <h2>The title</h2>
    <span>The content</span>
    <a ng-click="closeModal()">Close</a>
  </div>
</div>

<div ng-controller="ModalCtrl">
    <a ng-click="openModal('xyz')">Open it up</a>
</div>

Just totally doesn't work.. couldn't be more confused

Edit: updated with jsfiddle: http://jsfiddle.net/TeYfY/

Upvotes: 0

Views: 1916

Answers (1)

Josh David Miller
Josh David Miller

Reputation: 120513

I haven't checked your code in detail, but your ngClick is defined outside the ngController, so it doesn't have access to the openModal function. You would need it inside the controller to access a method on the scope, e.g.:

<div ng-controller="ModalCtrl">
  <div ng-show="modal()" class="modal_window">
    <h2>The title</h2>
    <span>The content</span>
    <a ng-click="closeModal()">Close</a>
  </div>

  <a ng-click="openModal('xyz')">Open it up</a>
</div>

If there are more problems than this, please feel free to post a Plunker or jsFiddle and update your question I'd be happy to take a closer look and revise my answer.

PS: This code belongs in a directive.

Update

The OP mentioned in the comments that he wants to control the modal from another location. This is often accomplished with a service:

module.factory( 'ModalService', function () {
  var is_visible = false;

  return {
    isVisible: function ( value ) {
      if ( angular.isDefined( value ) ) {
        is_visible = value;
      } else {
        return is_visible;
      }
    }
  };
});

In the modal directive, one can listen for the state on the service:

$scope.$watch( ModalService.isVisible, function ( status ) {
  $scope.isVisible = status;
});

And from a far-off controller, one can change the status on the service:

$scope.openModal = function () {
  ModalService.setVisible( true );
}

This is highly contrived and overly-simplified, but it should illustrate the point. In addition to services, one could also use events to accomplish inter-component communication, but in most cases services are more clean.

Upvotes: 3

Related Questions