简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM