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

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

本文关键字:函数 链接 变量 指令 ng-controller      更新时间:2023-09-26

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

Html 内容 - 索引.html 作为,

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

应用程序.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

我在这里错过了什么?

你只需要在指令中的数据中加入一些东西,例如:-

<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(); 如果您更改作用域中的某些内容以运行摘要周期,则需要。

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

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

您也可以使用 scope.$parent ,但请仅在您绝对确定的情况下执行此操作,因为它会创建对父范围的依赖

在绑定方法中未达到摘要周期。因此,您需要使用$apply方法:

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

使用 ngModel 它是双向绑定的默认

请参阅此示例:http://jsfiddle.net/4hxfghp1/1/

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

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