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)

「@ ローカル スコープ プロパティは、ディレクティブの外部で定義された文字列値にアクセスするために使用されます」 - http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

于 2015-10-05T18:13:53.080 に答える