2016-01-05 59 views
1

我想獲取點擊使用指令的參數。我想要獲取點擊事件中的孩子數據來檢查是否有孩子。將參數傳遞給角度指令點擊

.....

HTML

div ng-app="treeApp"> 
<ul> 
    <treeparent></treeparent> 

</ul> 

JS

(function() { 
var treeApp = angular.module('treeApp', []); 
treeApp.directive('treeparent', function() { 
    return { 
     restrict: 'E', 
     template: "<button addchild child='m'>ajith</button><div id='new'></div>" 
    } 
}); 
treeApp.directive('addchild', function ($compile) { 

    return { 
     scope: { 
      'child':'=' 
     }, 
     link: function (scope, element, attrs) { 
      debugger; 
      element.bind("click", function (scope,attrs) { 
       debugger; 

//here i want to get hild ie 'm' 
angular.element(document.getElementById('new')).append("<div><button button class='btn btn-default'>new one</button></div>"); 


       }); 
     } 
    } 

}); 
})(); 

plz幫助我

+1

問題是什麼? 'scope.child'不起作用? –

+0

是scode.child未定義 – Ajith

+0

它將是'scope.child'。另外**刪除**這個'angular.element(document.getElementById('new'))。append(「

」);' - 直到你在完全錯誤的方向上走得太遠。 – dfsq

回答

1

所以,我覺得scope.childundefined因爲它在聲明事件中存在重疊。

您可以事件綁定

link: function (scope, element, attrs) { 
     var child = scope.child; 
     element.bind("click", function (scope,attrs) { 

      // here you can use child 
      console.log('child', child); 

     }); 
    } 

或聲明參數名不同

link: function ($scope, $element, attrs) { 
     element.bind("click", function (scope,attrs) { 

      // here you can use $scope.child 
      console.log('$scope.child', $scope.child); 

     }); 
    } 

是一個回調有scopeattrs參數之前定義的變量?可能它只有一個$event的說法?

link: function (scope, element, attrs) { 

     element.bind("click", function ($event) { 

      // here you can use child 
      console.log('child', scope.child); 

     }); 
    } 
+0

Anton,對不起,它不是 – Ajith

+0

'bind'的回調只有一個'$ event'參數 –

+0

是從控制器調用指令功能的任何方式 – Ajith

0

用於從指令中父範圍呼叫方法

父模板

<test-dir data-method="myFunc"></test-dir> 
<button ng-click="myFunc('world')">click me</button> 

<button test-dir data-method="myFunc" ng-click="myFunc('world')">click me</button> 

指令實施例

.directive('testDir', function() { 
    return { 
     scope: { 
      method: '=', 
     }, 
     controller : function($scope) { 

      $scope.method = function(text) { 
       alert('hello '+text); 
      }; 

     }, 
    }; 
})