将函数动态添加到角度对象

时间:2016-03-01 14:21:37

标签: javascript jquery angularjs dynamic

如何将函数添加到对onclick或click事件有动态的角度对象?

添加onclick = {{item.function}}或ng-click = {{item.function}}无法正常工作

JS

angular
  .module('app', [])
  .controller('MainController', ['$scope', function($scope) {
    $scope.test = function() {
      alert(1);
    };
    $scope.items = {
      'item1': {
        name: 'Item1',
        function: 'test()' // Not calling
      }
    };
  }]);

HTML

<html ng-app="app">
<body ng-controller="MainController">
  <ul ng-repeat="item in items">
    <li ng-bind="item.name" ng-click="item.function"></li>
  </ul>
</body>
</html>

不工作演示 http://codepen.io/anon/pen/jqEKRP

1 个答案:

答案 0 :(得分:2)

在控制器中:

...
      'item1': {
        name: 'Item1',
        f: $scope.test
      }
...

在模板中:

<li ng-bind="item.name" ng-click="item.f()"></li>

http://codepen.io/bparnikel/pen/bpNjoE