无法读取控制器中的指令值

Cannot read directive value in controller

本文关键字:指令 控制器 读取      更新时间:2023-09-26

尝试实现一个可以从其grid-url指令读取URL参数的表。稍后,这个将提供给控制器中的$http。然而,它似乎并没有像预期的那样工作。值总是undefined

标记如下:

<table class="table table-striped" grid-url="http://localhost/records/all">
  ...
</table>
下面是相关的初始化代码片段:
app.directive('gridUrl', function(){
    return {
        replace: true,
        link: function(scope, element, attrs){
            // Add the gridUrl property to the scope
            scope.gridUrl = attrs.gridUrl;
        }
    }
});
app.controller('Ctrl', function($scope){
    // Expect to get http://localhost/records/all, but get undefined instead
    console.log($scope.gridUrl);
});

看起来不像是作用域隔离的问题。当在控制器本身调用console.log($scope)时,最奇怪的事情是我可以看到$scope.gridUrlhttp://localhost/records/all

那么是什么导致属性gridUrl在控制器中未定义呢?

你应该在控制器中定义gridUrl,然后用你的指令绑定它:

<div ng-controller="Ctrl" ng-init="$scope.gridUrlAttr = 'http://localhost/records/all'">
    <table class="table table-striped" grid-url-attr="$scope.gridUrlAttr">
        ...
    </table>
</div>
app.directive('gridUrl', function(){
    return {
        replace: true,
        scope: {
            gridUrlAttr: "="
        },
        link: function(scope, element, attrs){
            // Add the gridUrl property to the scope
            console.log(scope.gridUrlAttr);
            // here you can change the gridUrlAttr value
        }
    }
});
app.controller('Ctrl', function($scope){
    // Expect to get http://localhost/records/all, but get undefined instead
    console.log($scope.gridUrlAttr);
});

首先定义控制器。所以在作用域中没有属性gridl。你必须使用共享服务将指令注入到控制器中。

您可以使用service在模块之间共享数据:

    app.factory('SharedService', function() {
      return {
        sharedObject: {
          value: ''
        }
      };
    });`

这是因为先调用了控制器,然后才编译了指令。因此,gridUri值在控制器调用后的几个周期内到达作用域。

证明你可以在模板中输出这个变量:

<table class="table table-striped" grid-url="http://localhost/records/all">
  test :: {{ gridUrl }}
</table>

登录到控制台后,它将显示$作用域中的属性。(当它是一个对象时,它在控制台中更新)

根据你需要这个变量的目的,你可以把手表放在它上面,当它出现在作用域中时触发一些动作,或者你可以重新设计你提供数据的方式(例如,添加一些共享的UI模型服务)

找到了在保持结构不变的情况下使其成为可能的方法。这里的技巧是在10毫秒内使用$timeout服务。

app.controller('Ctrl', function($scope, $timeout){
  $timeout(function(){
     // Getting http://localhost/records/all as expected
     console.log($scope.gridUrl);
  }, 10);
});