繁体   English   中英

ng-controller变量在指令的链接函数中不可见

[英]ng-controller variables are not visible in directive's link function

我正在尝试读取指令的链接函数中ng-controller函数内部初始化的变量。

HTML内容-index.html,

<div ng-controller="skCtrl">
     <span sk-custom>click</span>
</div>

app.js,

app.controller('skCtrl',  function ($scope, $element) {
  $scope.data = "hello world"
})

app.directive("skCustom", function(){
  return {
    scope: {
      data: "="
    },
    link: function(scope, elem, attr){
      elem.bind("click", function(){
        //both the statements throw error...
        console.log(data)
        console.log(scope.data)
      })
    }
  }
})

当我单击鼠标时,它将引发错误,

data is undefined

我在这里想念什么?

您正在使用绑定创建隔离范围。 您可以删除scope:{}也可以通过指令设置绑定。

<sk-custom data="data"></sk-custom>

您也可以使用scope.$parent ,但是只有在绝对确定的情况下,才这样做,因为它会建立对父范围的依赖

您只需要指令中的数据即可,例如:

<span sk-custom data="name">click</span>

如在控制器中我定义的名称:-

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

指令代码:-

app.directive("skCustom", function(){
  return {
    scope: {
      data: "="
    },
    link: function(scope, elem, attr){
      elem.bind("click", function(){
        //both the statements throw error...
        console.log(scope.data)
      })
    }
  }
});

柱塞

数据未定义

发生这种情况是因为指令中未定义数据,而scope.data必须从指令模板传递。

PS:-scope。$ apply(); 如果您更改范围以运行摘要周期,则必须使用。

绑定方法未达到摘要循环。 因此,您需要使用$ apply方法:

link: function(scope, elem, attr){
      elem.bind("click", function(){
        console.log(scope.data);
        scope.$apply();
      })
    }

使用ngModel,默认为双向绑定

请参见以下示例: http : //jsfiddle.net/4hxfghp1/1/

  

它将为您提供控制器的孔范围

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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