0

I have a directive and I want to call a method of the Directive from outside controller . That means when I click a button in the main controller , I want to hide a component in the directive . Is this really possible ,If yes please help me .

Kamal

4

2 回答 2

0

You can accomplish this by allowing your directive to listen to a scoped property from your controller. Using isolated scope and the =, you can tell your directive what to pay attention to in order to hide its component:

Html:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <h1>Hello Plunker!</h1>
    <button ng-click="action()">Toggle</button>
    <the-directive show-component="showIt"></the-directive>
  </body>

</html>

JavaScript:

var myApp = angular.module('myApp', []);

myApp.controller('Ctrl', function($scope) {


  $scope.showIt = true;

  $scope.action = function() {

    $scope.showIt = !$scope.showIt;
  }

  });


  myApp.directive('theDirective', function() {

    return {
      restrict: 'E',
      scope: {
        'showComponent': '='
      },
      template: '<div><div ng-show="showComponent">show Me!</div></div>'

    }
  })

Here is a plunker demonstrating the technique.

于 2013-11-08T09:36:37.993 回答
0

To call directive methods outside in a controller I would share a directive control object with the controller. Inside the controller you can call methods of this control object and they get executed inside your directive.

  1. create a control object inside your directive
  2. share this control object with the controller using tw data binding
  3. call methods on this control object inside your controller

here is a plunker that demonstrates it: http://plnkr.co/edit/MqN9yS8R5dnqTfjqldwX?p=preview

于 2013-11-08T11:48:17.340 回答