2014-01-26 126 views
0

我在我的一個指令中使用範圍隔離。然而,這似乎並沒有工作:Angularjs 1.2.9範圍隔離

<div ng-controller="MyCtrl"> 
    Hello, {{name}}! 
    <dir info='spec'> 
     {{ data }} 
    </dir> 
</div> 

var myApp = angular.module('myApp',[]); 

//myApp.directive('myDirective', function() {}); 
//myApp.factory('myService', function() {}); 

function MyCtrl($scope) { 
    $scope.name = 'Superhero'; 
    $scope.spec = 'Super'; 
} 

myApp.directive('dir', function(){ 
    return { 
     restrict: 'AE', 
     scope:{ 
     data: '=info' 
     } 
    } 
}); 

小提琴:enter link description here

回答

2

這裏是一個小提琴:無論是在定義的http://jsfiddle.net/WA5t5/

由於this commit1.2)子元素應用程序模板或其他某些 指令模板不會得到隔離範圍。如果你想改變這種行爲檢查我的其他答案

myApp.directive('dir', function(){ 
    return { 
     restrict: 'AE', 
     scope:{ 
     data: '=info' 
     }, 
     template: "{{ data }}" 
    } 
}); 

你可以做到這一點,而不是Why I can't access the right scope?

0

嘗試:

myApp.directive('dir', function(){ 
    return { 
     restrict: 'AE', 
     scope:{ 
     data: '=info' 
     }, 
     template:"<div>{{data}}</div>" 
    } 
}); 

DEMO

使用transclusion的範圍自己綁定的另一個解決方案:

myApp.directive('dir', function(){ 
    return { 
     restrict: 'AE', 
     scope:{ 
     data: '=info' 
     }, 
     transclude:true, 
     compile: function (element, attr, linker) { 
      return function (scope, element, attr) { 
      linker(scope, function(clone){ 
       element.append(clone); // add to DOM 
      }); 
      }; 
     } 
    } 
}); 

可以仍然使用相同的HTML作爲之前:

<div ng-controller="MyCtrl"> 
    Hello, {{name}}! 
    <dir info='spec'> 
     {{data}} 
    </dir> 
</div> 

DEMO

0

你應該在你的指令定義了一個模板,其中顯示有數據範圍變量。 html代碼不知道數據範圍變量是什麼,它只在指令模板中知道。看到這個demo

myApp.directive('dir', function() { 
    return { 
     restrict: 'AE', 
     scope: { 
      data: '=info' 
     }, 
     link: function (scope, element, attrs) { 
      console.log(scope.data); 
     }, 
     template: 'Hello {{data}}' 
    } 
});