Adding a Controller to a Directive

You can add a custom controller to a directive by using the controller property of the directive definition. This allows you to provide controller support for the directive template. For example, the following code adds a simple controller that sets up a scope value and function:

directive('myDirective', function() {
  return {
    scope: {title: '='},
    controller: function ($scope){
      $scope.title = "new";
      $scope.myFunction = function(){
      });
    }
  };
});

You can also use the require option to ensure that a controller is available to the directive. The require option uses the require:'^controller' syntax to instruct the injector service to look in parent contexts until it finds the controller. The following is an example of requiring the myController controller in a directive:

directive('myDirective', function() {
  return {
    require: '^myController'
  };
});

When you add the require option, the specified controller is passed as the fourth parameter of the link() function. If you specify the name of another directive in the require option, the controller for that directive is linked.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.7.154