使用隔离范围时从指令调用控制器的功能?

时间:2018-08-28 12:14:33

标签: angularjs angularjs-scope angular-directive isolated-scope

我想从Controller调用Directive的函数,用于验证。但是,当我使用隔离范围时,我对如何从Directive调用感到有些困惑。这是指令的代码:-

App.directive('test',function(){
    return{
    require: "ngModel",
     scope:{
         a:"=",
         b:"=",
         c:'=',
         d:'='
            },
         link: function(scope, element, attributes,modelVal )
            {
            modelVal.$validators.test= function(val)
              {
                return false;
               //isolated scope values will make if condition true or false.
               if(scope.a=="true"){
                //I need to call a function of controller here. But how can 
                //i call that function from directive? this is my problem
                         } 
               }
             scope.$watch("a", function()
               {
                    modelVal.$validate();
                });

         }//end of link function;
      }//end of return;
});//end of directive;

Function在我的controller中,我认为我不需要写controller code。在我的html中,我将此指令称为:

     <test a="1" b="2" c="3" d="4" ng-model="abc"></test>

我需要在directive中进行什么更改才能调用controller function的{​​{1}}?

2 个答案:

答案 0 :(得分:1)

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

module.controller('TestController', function($scope){
  $scope.text = 'test';
  
  // Will be invoked from 'test' directive
  $scope.alertMe = function(text){
    alert(text);
  };
});

module.directive('test', function(){
  return {
    restrict: 'E',
    template: '<input ng-model="text" ng-change="onChange(text)" />',
    scope: {
      text: '='
    },
    link: function(scope, elem, attr){
      scope.onChange = function(text){
      
      // Invoking parent controller function
       scope.$parent.alertMe(text);
      }
    }
  }
})
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myModule" ng-controller="TestController">
 
<test text="text"></test>

</div>
</body>
</html>

答案 1 :(得分:0)

我给了一个样品,像这样尝试。

控制器

module.controller('TestController', function($scope){
  $scope.onTextChange = function(text){
    alert(text);
  };
})

HTML:

<test my-func="onTextChange(text)"></test>

指令:

module.directive('test', function(){
  return {
    restrict: 'E',
    template: '<input ng-model="text" ng-change="onChange(text)" />',
    scope: {
      myFunc: '&'
    },
    link: function(scope, elem, attr){
      scope.onChange = function(text){
        if(typeof scope.myFunc === 'function'){
          // Calling the parent controller function
          scope.myFunc({text: text});
        }
      }
    }
  }
})