AngularJS - 如何从链接函数访问隔离范围?

时间:2013-05-27 12:22:10

标签: angularjs angularjs-directive

请考虑以下指令示例:(Live Demo)

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。为什么?如何从链接功能访问隔离范围?

2 个答案:

答案 0 :(得分: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
    }
  };
});  

答案 1 :(得分:0)

由于@ isolate scope只能传递字符串,因此您唯一的选择是

console.log(attrs.tel)

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