【问题标题】:how to pass a value from attrs.$observe in an angular directive如何在角度指令中从 attrs.$observe 传递值
【发布时间】:2015-02-13 20:55:14
【问题描述】:

目前,console.log(value) 输出 'lat' 的值,但如果我尝试在指令的其他位置访问该值,它将不起作用。我试图设置一个等于 attrs.$observe 的变量,并将 attrs.$observe 放在一个函数中。另外由于某种原因,我无法返回数据的值。有什么想法

 angular.module('Ski').directive('mapCanvas', function() {
  function link (scope, element, attrs) {
    attrs.$observe('lat', function(data) {
      console.log(data);
    });
  }
}

【问题讨论】:

  • 你能举例说明你是如何在指令的其他地方尝试访问它的吗?

标签: angularjs angularjs-directive


【解决方案1】:

您只需使用scopevar 制作一些全局变量即可完成此操作

代码

angular.module('Ski').directive('mapCanvas', function() {
  function link (scope, element, attrs) {
    scope.lat = ''; //or it can be var lat = '';
    attrs.$observe('lat', function(data) {
      scope.lat = data; //or it can be var scope.lat = '';
      console.log(data);
    });
    scope.test = function(){
       //when it gets called
       console.log(scope.lat);
    }
  }
}

希望这可以帮助你。谢谢。

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 1970-01-01
    • 2018-09-03
    • 2016-12-19
    • 2015-06-28
    • 2020-09-22
    • 2019-05-05
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多