2013-10-03 175 views
0

我一直在這個特定的測試我的頭幾個小時。我相信所展示的指令應該可以工作,但我正在傳遞給隔離範圍的值未定義。AngularJS隔離範圍沒有被傳遞到指令

代碼:

HTML

<!doctype html> 
<html ng-app="myApp"> 
<body> 
    <a ng-href="#" class="test-scope" name="test">Console should say 'test' but gives undefined</a> 
</body> 
</html> 

的JavaScript

angular.module('myApp', []) 
    .directive('testScope', function() { 
     return { 
      restrict: 'C', 
      scope: { 
       name: "=" 
      }, 
      link: function(scope, element, attrs) { 
       console.log(scope.name); 
      } 
     }; 
    }); 

這裏的小提琴:http://jsfiddle.net/jPtb3/8/

任何幫助將是AP preciated,我一定在做錯事。

+0

改變你的小提琴,看 –

回答

1

變化=@

angular.module('components', []) 
.directive('testScope', function() { 
    return { 
     restrict: 'C', 
     scope: { 
      name: "@" 
     }, 
     link: function(scope, element, attrs) { 
      console.log(scope.name); 
     } 
    }; 
}) 

angular.module('myApp', ['components']); 

見固定Fiddle

@ - 結合父作用域屬性的值(它總是一個字符串)本地範圍。

= - 直接綁定父作用域屬性,這將在傳遞之前評估

+0

看到這個鏈接:http://amitgharat.wordpress.com/2013/06/08/the-hitchhikers-guide-to-the-directive/。你可以找到例子和描述 –

1

您正在解釋不正確的隔離範圍構造。

當你說name=你說的是在指令聲明html上有屬性name和任何屬性值存在的綁定到作用域中的屬性名。

在這種情況下,聲明指令的範圍中應該有一個範圍屬性名稱test。指令範圍上的name屬性將指向父測試屬性(不是字面意思)

底線您的指令範圍name - >容器範圍test屬性。

見我plunker這裏http://jsfiddle.net/cmyworld/ANzUf/

+0

我不明白下。我的標籤有一個name =「test」的屬性 - 這不是你要求我做的嗎? –

+0

@ francisco.preller我已添加小提琴。看到我在這裏說的行動http://jsfiddle.net/cmyworld/ANzUf/ – Chandermani

+0

我明白了,現在它很有道理。謝謝(你的)信息! –

相關問題