2014-10-18 108 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