2014-05-07 40 views
1

下面是我如何從點擊獲取範圍。有沒有更簡單的方法來獲取子範圍?謝謝。angularjs從點擊元素獲取當前範圍

.chatMsg(ng-repeat='chatMsg in chatLog', ng-class="{active: detailed}", ng-click="openChatDetail($event)") 
    .text {{chatMsg.foo}} 

    $scope.openChatDetail = function(e) { 
    var childScope = angular.element(e.currentTarget).scope() 
    if (childScope.detailed) { 
     childScope.detailed = false 
     return 
    } 

    childScope.detailed = true; 
    } 

我想,當它在詳細模式年開幕活動類添加到聊天消息。

+1

請提供一些詳細信息,關於你想要做什麼,跨越示波器將阻礙您單元測試控制器的能力。可能有更好的方法,而不是直接訪問子範圍。 – Brocco

+0

@Brocco你說得很對不起,我添加了這個信息。 – Harry

回答

0

兒童範圍,發出事件出來它的父作用域(S)

$scope.$emit('event name', {param: value}); 

和你的父母範圍監聽和處理事件

$scope.$on('event name', function (params){}); 

documentation

0

如果我理解得很好,chatMsg是一個指令。這意味着您可以在指令的控制器中指定您的openChatDetail方法,其中範圍將作爲指令的範圍。

yourApp.directive('chatMsg', [ 
    function(){ 
     return { 
      ..., 
      scope: true, /* or even better, isolated scope */ 
      controller: function(scope, elem, attrs) { 
       scope.openChatDetail = function() { 
        ... 
       } 
      } 
     } 
    } 
]) 
0

爲什麼你不這樣做,而不是:

.chatMsg(ng-repeat='chatMsg in chatLog', ng-class="{true: 'active'}[chatMsg.detailed]", ng-click="openChatDetail(chatMsg)") .text {{chatMsg.foo}} 

在你控制器

$scope.openChatDetail = function(item) { 
     item.detailed = !(item.detailed) || true; 
    }