简单的隔离范围函数参数未调用

时间:2015-09-03 14:09:00

标签: javascript angularjs angularjs-directive

我试图调用隔离的范围函数。该函数是removeFriend(item)take和item并从数组中删除它。它是从一个名为removeFriend的指令调用的,它发送一个函数方法=" removeFriend(item)"要删除的项目,"方法"是指令notifyParent中的函数参数的名称:'& method'。当我点击删除按钮时,指令的功能已到达但它不会调用父函数。

以下是代码:

这是html:

<div class="panel panel-primary">
<div class="panel-heading" ng-click="collapse()">{{user.name}}</div>

<h4>Friends</h4>
<ul>
  <li ng-repeat='item in user.friends'>
    {{item}}

    <!-- This is the directive with the function I want to call -->
    <remove-friend method="removeFriend(item)"></remove-friend>
  </li>
</ul>

这是控制器:

var myapp = angular.module('app', []);

angular.module('app').controller("mainCtrl", function($scope) {
$scope.a = "abc";
var a = a;



$scope.user1 = {
  name: "Diego",
  address: {
    street: 'Santa Fe 654 2e',
    city: 'Córdoba',
    planet: 'Pluton'
  },
  friends: ['Amigo 1', 'Amigo 2']
}

$scope.user2 = {
  name: "Juan",
  address: {
  street: 'Santa Fe 654 2e',
  city: 'Córdoba',
  planet: 'Pluton'
  },
  friends: ['Amigo 1', 'Amigo 2']
}



 $scope.removeFriend = function(friend) {
    console.log('hello');
    var idx = $scope.user.friends.indexOf(friend);

    if (idx > -1) {
      $scope.user.friends.splice(friend, 1);
    }
  }

});

这是指令模板:

<button class="btn btn-xs btn-success" ng-click="confirmRemove()">Remove</button>

这是指令定义:

myapp.directive('removeFriend', function() {
 return {
    restrinc: 'E',
    templateUrl: 'removeFriend.html',
    scope: {
       notifyParent: '&method'
    },
    controller: function($scope) {

    //Function that calls the parent function removeFriend(friend)
      $scope.confirmRemove = function(){
       console.log('removing');
       $scope.notifyParent();
      }
    }
   }
 })

1 个答案:

答案 0 :(得分:0)

要验证的一些事项:

  • 停用Chrome缓存
  • 确保ng-controller位于范围数据的最外层div标签上(上面没有看到它,但假设你把它留了?)
  • 您有'限制'错误

查看此plnkr:http://plnkr.co/edit/14qKAyclJUg9uCItLDma?p=preview

对于此示例,我确实将$scope.user1更改为$scope.user