0

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');
                    };
                    });

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

so with above code in question just add properties as you mentioned you shoudl work , how about link function , do i still need it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.