加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 多指令[ngController,…]要求新/隔离范围

发布时间:2020-12-17 17:04:32 所属栏目:安全 来源:网络整理
导读:我有以下( https://jsfiddle.net/hhgqup4f/5/): div parent parent-model="vm.model1" ng-controller="Controller as vm" Parent/div 控制器是: app.controller("Controller",Controller);function Controller() { var vm = this; vm.model1 = "My Model 1
我有以下( https://jsfiddle.net/hhgqup4f/5/):

<div parent parent-model="vm.model1" ng-controller="Controller as vm">
   Parent
</div>

控制器是:

app.controller("Controller",Controller);

function Controller() {
  var vm = this;
  vm.model1 = "My Model 1";
  vm.model2 = "My Model 2";
}

然后我有一个如下指令:

app.directive("parent",parent);

function parent() {

  var parent = {
    controller: ["$scope",controller],replace: false,restrict: "A",scope: {
      model: "="
    }
  };

  return parent;

  function controller($scope) { 
    console.log($scope.model);
  } 

}

使用parent-model =“vm.model1”,我试图说明指令应该使用控制器中的哪个属性.但是当我在指令中执行console.log($scope.model)时,我得到错误:

"Error: [$compile:multidir] Multiple directives [ngController,parent (module: app)] asking for new/isolated scope on: <div parent="" parent-model="vm.model1" ng-controller="Controller as vm">

怎么解决这个?

解决方法

错误 …

"Error: [$compile:multidir] Multiple directives [ngController,parent (module: app)] asking for new/isolated scope on: <div parent="" parent-model="vm.model1" ng-controller="Controller as vm">

…非常具有说明性,因为AngularJS不允许多个指令(在相同的DOM级别上)创建自己的隔离范围.

根据documentation,强制实施此限制是为了防止$scope对象的冲突或不受支持的配置.

通常,指令随隔离范围一起提供,其意图是组件化或重用附加到DOM的一些逻辑/动作.

因此,有意义的是,两个可重用的组件不能合并在一起以产生组合效果(至少在AngularJS中).

更改您的指令用法,以便从其直接父级(在本例中为ngController指令)提供所需的属性.

<div ng-controller="Controller as vm">
  <div parent parent-model="vm.model1"></div>
</div>

同样,您可以以规范化格式访问传递的属性到指令的隔离范围:

app.directive('parent',function(){
  return {
    scope: {
       parentModel: '='  // property passed from the parent scope
    },controller: function($scope){
       console.log($scope.parentModel); 
    }
  };
});

Demo

指令传播指令

如前所述,具有隔离范围的两个或多个指令不能在同一DOM元素上使用.但是,其中一个指令可能具有独立的范围.在这种情况下,其他指令可以根据需要通过要求其控制器进行通信:

<div dir-isolate dir-sibling></div>

...

.directive('dirIsolate',function(){
  return {
    scope: {},controller: function(){
      this.askSomething = function(){
         return 'Did you ask for something?';
      };
    }
  };
})
.directive('dirSibling',function(){
  return {
    require: 'dirIsolate',// here is the trick
    link: function(scope,iElement,attrs,dirSiblingCtrl){ // required controller passed to the link function as fourth argument
       console.log(dirSiblingCtrl.askSomething());
    }
  };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读