2014-01-26 204 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}}' 
    } 
});