0

我已經創建了一個指令,它有一個隔離的範圍。不知何故,當我試圖從指令的元素獲取範圍時,它給了我控制器的範圍,而不是隔離範圍。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> 

DEMO is here

+0

你不需要從元素中獲取範圍,用'$ scope'替換'element.scope()'。 – haki 2014-10-01 07:40:34

+0

而「模型」綁定似乎並沒有創建任何額外的隔離範圍。這就是您收到組件範圍的原因。 – jevgenig 2014-10-01 07:44:16

+0

@haki是的,我知道。但我需要從*元素*中檢索範圍。這是必須的。 – Engineer 2014-10-01 07:45:25

回答

0

你需要改變這一行:

console.log("element scope id->", element.scope().$id); 

爲此:

console.log("element scope id->", $scope().$id); 

如果你想從該元素的範圍,這樣做:

console.log("element scope id->", element.isolateScope().$id); 

通知調用isolateScope。請參閱https://docs.angularjs.org/api/ng/function/angular.element#methods

0

在您的指令中,您已通過創建它自己的作用域對象作爲私有作用域。範圍:{model:'='}。這就是爲什麼element.scope()實際上是父級的範圍。

這裏有幾個事實:

  • 指令的範圍$()$父= element.scope()
  • 家長無法訪問的孩子的範圍。儘管有一些像element.scope()。$$ childHead這樣的解決方法,但它不被推薦,並且它一直不工作。爲了與孩子的父母進行交流,你可以使用$ scope()。$ broadcast('event-name',param1,param2),並使用$ scope從$ child中捕獲事件。$ on('event-name ',函數($ parentScope,param1,param2){...})
  • 您可以使用$ scope()。$ parent.methodName()直接調用父級方法或訪問父級模型,從子級到父級進行通信,或者使用類似$ scope()。$ emit('event-name',param1,param2)的事件觸發,並且使用$ scope從父項中捕獲事件$ on('event-name',function($ childScope,param1,param2 ){...})

希望這會有所幫助。