这里我使用 personManager 作为控制器,使用 myPersonDirective 作为指令。
myDirective.js
var myDirModule = angular.module('myDirApp', []); var personManager = function() { var personManageInst = this; personManageInst.personsData = [ {name: "Sam", age:33, city:"Delhi"}, {name: "Mac", age:22, city:"Mumbai"}, ]; personManageInst.addNewMember = function() { personManageInst.personsData.push({name: personManageInst.name, age: personManageInst.age, city: personManageInst.city}); }; }; var myPersonDirective = function() { return{ restrict: "AE", templateUrl: "personsTemplate.html", scope: { pers: "=", index: "@" }, controller: function($scope){ $scope.deletePerson = function(index) { console.log(index); output: index no. personManageInst.personsData.splice(index, 1); //output: personManageInst is undefined }; } } }; myDirModule.controller("myPerCont", personManager).directive("personDir", myPersonDirective);
personsTemplate.html
<tr> <td>{{pers.name}}</td> <td>{{pers.age}}</td> <td>{{pers.city}}</td> <td> <button type="button" ng-click="deletePerson(index)">Delete</button> </td> </tr>
myApp.html
<!DOCTYPE html> <html> <head>add title, css, scripts</head> </html> <body> . . . <tr person_dir pers="perso" index="{{$index}}" ng-repeat="perso in personManageInst.personsData"></tr> . . </body>
答案 0 :(得分:0)
您的deletePerson函数应该在控制器中。 ng-repeat需要 - 通过$ index&#39;跟踪,然后你可以调用该函数。