我已經創建了一個指令,它有一個隔離的範圍。不知何故,當我試圖從指令的元素獲取範圍時,它給了我控制器的範圍,而不是隔離範圍。scope()方法在Angular JS中如何工作?
我的代碼有什麼問題?誰可以解釋scope()方法是如何工作的?
這是我的js代碼:
angular.module('myApp',[])
.directive('component',function(){
return {
restrict:'EA',
replace:false,
scope:{
"model":"="
},
template:'<div>{{model.name}}</div>',
link:function($scope,element,attrs){
element.bind('click',function(event){
console.log("element scope id->", element.scope().$id);
});
}
};
})
.controller('AppCtrl',function($scope){
$scope.myModel = {
name:"Click me, to see scope's id in console"
};
console.log("controller scope id->", $scope.$id);
});
和標記:
<div ng-app="myApp" ng-controller="AppCtrl">
<component selectable model="myModel"></component>
</div>
你不需要從元素中獲取範圍,用'$ scope'替換'element.scope()'。 – haki 2014-10-01 07:40:34
而「模型」綁定似乎並沒有創建任何額外的隔離範圍。這就是您收到組件範圍的原因。 – jevgenig 2014-10-01 07:44:16
@haki是的,我知道。但我需要從*元素*中檢索範圍。這是必須的。 – Engineer 2014-10-01 07:45:25