简体   繁体   中英

Adding function dynamical to angular objects

How to add a function to a angular object dynamical to the onclick or click event?

Adding onclick={{item.function}} or ng-click={{item.function}} won't work

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>

Not working demo http://codepen.io/anon/pen/jqEKRP

In controller:

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

In template:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM