hussain
hussain

Reputation: 7083

How to use controller in AngularJs directives?

I have a controller that i want to use in my directive, how can i use controller for directive i want to access all controller functions in directive ?

directive.js

angular.module('App').directive('deleteButtons', function (prcDeleteFactory,$rootScope) {
  'use strict';
  return{
    restrict:'E',
    scope:{
    id: '=ids',
    name: '@'
    },
    templateUrl:'scripts/common/prcDeleteDirective.html',
   link:function(scope){
     scope.deleteButton = function(){
       if(scope.name === 'process') {
         prcDeleteFactory.deleteObj(scope.name,scope.id);
         $rootScope.$broadcast('event');
       } else if(scope.name === 'risk') {
         prcDeleteFactory.deleteObj(scope.name,scope.id);
       } else if(scope.name === 'control'){
         prcDeleteFactory.deleteObj(scope.name,scope.id);
       }
     }
   }     
  }

});

Ctrl.js

angular.module('App').controller('ProcessCtrl', function($scope) {
                    'use strict';
                    $scope.confirmationWin = function(){
                    console.log('Print value');
                    };
                    });

Upvotes: 0

Views: 49

Answers (2)

Arkantos
Arkantos

Reputation: 6608

You can define a controller using an anonymous function or by passing the string of an existing controller function registered on the same module like below.

return {
      restrict:'E',
      controller : 'ProcessCtrl'
  };

As you're using an isolated scope for your directive, to access controller properties and methods, you had to define the controller explicitly.

In case you don't want to use an isolated scope, you can remove the scope property from your Directive Definition Object that you're returning., The default value is false which means your directive will share the same scope as the enclosing container's controller. You can set scope : true which means your directive will get a new scope which prototypically inherits all methods and properties from the enclosing controller.

For more details on directive scopes, you can refer to this link.

Upvotes: 1

nathan.medz
nathan.medz

Reputation: 1603

in your directive you can use

controller : 'ProcessCtrl',
controllerAs: 'vm',
bindToController: true

and then access controller properties in your directive template with vm.confirmationWin for example

Upvotes: 0

Related Questions