单击函数不是从指令模板调用的

on-click function not called from a directive template

我是 Angular 的初学者,我想了解为什么在某些情况下我的 ng-click 无法正常工作,具体取决于上下文。 首先,这是我的代码,然后我会尝试更准确地描述我的问题。

HTML :

<div ng-app='myApp'>
   <section id="map-orders" ng-controller="ProductsController as products">
      <div class="product-box" ng-repeat="products in products.products | orderBy:'name'">
         <div class="product">
            <h3> {{products.name}} </h3>
            <span ng-click="remove($index)">Remove</span>
         </div>
      </div>
   </section>
</div>

JS :

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

app.controller('ProductsController', function(){
    this.products = products;   
    this.remove = function(index) {
        products.splice(index, 1);
    }
});

var products = [
    {
        name: "Carte 1", 
        generationDate: "03/03/2016",
    },
    {
        name: "Carte 2", 
        generationDate: "04/03/2016",
    }
];

所以这段代码有效。但是当我通过添加一个指令来转换它时: HTML :

<div ng-app='myApp'>
   <section id="map-orders" ng-controller="ProductsController as products">
      <div class="product-box" ng-repeat="products in products.products | orderBy:'name'">
         <product></product>
      </div>
   </section>
</div>

将此指令添加到原始 js 中:

app.directive('product', function() {
    var tpl = '<div class="product">' +
    '<h3 {{products.name}} </h3>' +
    '<span ng-click="remove($index)">Remove</span>'
    '</div>';
    return {
        restrict: 'E',
    template: tpl,
    };
});

我的 remove() 函数现在不起作用。我不明白为什么。 有人可以帮我吗?如果可能的话,特别是我的代码,所以我得到了问题。

提前致谢

因为您使用 controllerAs 语法,您需要在模板中为函数指定别名 remove

jsfiddle.

上的实例

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

myApp.controller('MyCtrl', function($scope) {
    this.products = [{
      name: "Alex",
    }, {
      name: "Sam"
    }];
    this.remove = function(index) {
      this.products.splice(index, 1);
    }
  })
  .directive("product", function() {
    var tpl = '<div class="product">' +
      '<h3> {{product.name}} </h3>' +
      '<span ng-click="my.remove($index)">Remove</span>'
    '</div>';
    return {
      restrict: 'E',
      template: tpl,
      link: function(scope) {
        console.log(scope);
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl as my">
    <div class="product-box" ng-repeat="product in my.products">
      <product></product>
    </div>
  </div>
</div>

P.S。你在模板中有错误。你没有关闭 h3 标签

此处您的指令仅使用与 ProductsController 相同的作用域。因此可以使用 products.remove($index) 调用 ProductsController 中的 remove 方法,因为您遵循 as controller 语法在 html

中指定控制器时