3

考虑以下指令示例:(现场演示)

app.directive('phone', function() {
  return {
    restrict: 'E',
    scope: {
      tel: '@'
    }, 
    template: '<div>{{tel}}</div>',
    link: function(scope, element, attrs) {
      console.log(scope.tel);   // undefined
    }
  };
});  

像这样使用:

<phone tel="1234"></phone>

tel在模板中可以访问,但在链接函数中是undefined. 为什么?如何从链接功能访问隔离范围?

4

2 回答 2

2

在链接功能完成之前它不会被插值(我不确定为什么会这样),但你有几个选择:

app.directive('phone', function($timeout, $interpolate) {
  return {
    restrict: 'E',
    scope: {
      tel: '@'
    }, 
    template: '<div>{{tel}}</div>',
    link: function(scope, element, attrs) {

      //Use $timeout service with no delay:
      $timeout(function(){
        console.log(scope.tel);   // 1234
      });

      //Use $watch - will get called every time the value changes:
      scope.$watch('tel',function(tel){
        console.log(scope.tel);   // 1234
      });

      //You can even use the $intrapolate service, this is basically what `@` does:
      console.log($interpolate(element.attr('tel'))(scope.$parent));

      // in your example tel isn't an expression but a constant so you could also do this:
      console.log(attrs.tel); // 1234
    }
  };
});  
于 2013-05-27T12:39:17.083 回答
0

由于@isolate 范围只能传递字符串,你唯一的选择是

console.log(attrs.tel)

“@local 范围属性用于访问在指令之外定义的字符串值” - http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

于 2015-10-05T18:13:53.080 回答