使用"要求"在指令,要求家长控制器 [英] Using "require" in Directive to require a parent Controller

查看:113
本文介绍了使用"要求"在指令,要求家长控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试规定父控制器(未指令),但AngularJS返回异常。在code是这样的:

JS

  app.controller(myController的功能($斯科尔){
    ...
});app.directive(myDirective功能($ Q){
    返回{
        要求:^ myController的
        模板:,
        链接:功能(范围,元素,ATTRS,myCtrl){
            ...
        }
    };
});

HTML

 < D​​IV NG控制器=作为myController的myCtrl>
    ...
        < D​​IV我-指令> ...< / DIV>
    ...
< / DIV>

错误


  

错误:[$编译:ctreq]控制器myController的,所要求的
  指令'myDirective,无法找到!


为什么呢?结果
也许,要求属性必须参考的控制器的指令

感谢


解决方案

需要在另一个指令使用其他指令的控制器,请参考下面的例子

  VAR应用= angular.module('对myApp',[]);//某个指令指向App.directive('oneDirective',函数(){  返回{
      限制:'E',
      控制器:函数($范围){       $ scope.myName =功能(){
            的console.log(MYNAME');
          }         }
    }});   // 2指令  App.directive('twoDirective',函数(){  返回{
      要求:用oneDirective'//某个指令指向,
      链接:功能(范围,ELE,ATTRS,oneCtrl){
         的console.log(oneCtrl.myName())
     }   }  })

I try to "require" a parent controller (not directive) but AngularJS returns an exception. The code is like this:

JS

app.controller("myController", function ($scole) {
    ...
});

app.directive("myDirective", function ($q) {
    return {
        require: "^myController",
        template: "",
        link: function (scope, element, attrs, myCtrl) {
            ...
        }
    };
});

HTML

<div ng-controller="myController as myCtrl">
    ...
        <div my-directive>...</div>
    ...
</div>

Error

Error: [$compile:ctreq] Controller 'myController', required by directive 'myDirective', can't be found!

Why?
Maybe, require property must be reference to a controller of directive?

Thanks

解决方案

Require is of using other directives controllers in another directive , please refer the below example

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

//one directive

App.directive('oneDirective',function(){

  return {
      restrict: 'E',
      controller:function($scope){

       $scope.myName= function(){
            console.log('myname');
          }

         }
    }

});

   //two directive

  App.directive('twoDirective',function(){

  return {
      require:'oneDirective' //one directive used,
      link : function(scope,ele,attrs,oneCtrl){
         console.log(oneCtrl.myName())
     }

   }

  })

这篇关于使用&QUOT;要求&QUOT;在指令,要求家长控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆