2014-10-18 88 views
0
Below is my code 

我創建了一個簡單的頁面並在其中包含一個指令。在ng中單擊指令我想調用父範圍的方法。Angular js指令問題

<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>Directive Page</title> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js">  </script> 
    </head> 
    <body> 
     <div ng-app="myapp" ng-controller="myController"> 
      <ul-dir on-item-click="itemClick(obj)"></ul-dir> 
     </div> 
    </body> 
</html> 

<script> 
    var myapp = angular.module("myapp", []); 
    myapp.directive('ulDir', function() { 
     return { 
      restrict: 'E', 
      replace: 'true', 
      template: '<div id="container"><ul><li ng-repeat="content in contents"><a href="#" ng-click="onItemClick(content)">{{content.name}}</a></li></ul></div>', 
      controller: function ($scope) { 
       $scope.contents = [{'name':'Nishu', 'age':'20'},{'name':'Nidhi', 'age':'21'},{'name':'Kirti', 'age':'24'}]; 
      }, 
      scope: { 
       onItemClick: '&'  // Pass a reference to the method 
      } 
     } 
    }); 
    myapp.controller('myController', function($scope) { 
     $scope.itemClick = function(content){ 
      console.log("Success : "+content); 
     }; 
    }); 
</script> 

所以我的控制檯日誌打印爲「成功:未定義」 所以內容對象不是從指令範圍傳遞給parentscope。

請幫幫我。

回答

1

我相信裏面的模板您的通話要麼是:

<a href="#" ng-click="onItemClick({'content':content})">

<a href="#" ng-click="onItemClick({'obj':content})">

你可以試試。欲瞭解更多詳情,請參閱此SO貼子Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

+0

謝謝..它的工作原理。 – Sunny 2014-10-18 08:44:58

+0

你好Chandermani。我有另一個問題,因爲我想在obj上面的函數中傳遞第二個參數。那麼幫助我什麼是語法? – Sunny 2014-10-21 08:06:18

+0

從指令代碼調用鏈接函數時,數據必須以對象格式'{}'傳遞。 – Chandermani 2014-10-21 09:00:21