将$ index作为参数从指令模板传递到指令控制器,并在指令控制器的函数中使用模块控制器的函数

时间:2015-10-23 10:40:12

标签: angularjs angularjs-directive angularjs-controller

  

这里我使用 personManager 作为控制器,使用 myPersonDirective 作为指令。

  • 如何将 $ index 从模板传递给deletePerson()函数。
  • 如何在deletePerson(index)中使用 personManageInst.person 对其执行splice()函数。
  

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>

1 个答案:

答案 0 :(得分:0)

您的deletePerson函数应该在控制器中。 ng-repeat需要 - 通过$ index&#39;跟踪,然后你可以调用该函数。