AngularJS set ng-click function with scope variables within ng-repeat

落花浮王杯 提交于 2019-12-06 10:32:55

http://plnkr.co/edit/QE50kpfBjXy2WPvjVsJc?p=preview

I've created a fork of your code. Your 'fn' reference were strings. I changed them to functions, and added '()' to the 'button.fn' in the template. I also changed where the function references were made since the definitions of the functions were in a different controller.

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

app.controller('MainCtrl', ['$scope', function($scope){
    $scope.notification = {
        ctrl: 'logout', 
        text: 'Logout?',
        buttons: [
    			{label:'Yes', fn: null},
    			{label:'No', fn: null},
        ],
    };
}]);

app.directive('notification', [
	function() {
		return {
		restrict: 'E', // E = Element, A = Attribute, C = Class, M = coMment
		templateUrl: 'notification.tpl.html',
		replace: true,
		link: function(scope, element, attrs) {
      //...
		}
	};
		
		
}])

app.controller('logout', ['$scope', function($scope){
  $scope.logout = function(){
      alert('logout');
  };
  $scope.cancel = function(){
      alert('cancel');
  };
  
  $scope.notification.buttons[0].fn = $scope.logout;
  $scope.notification.buttons[1].fn = $scope.cancel;
}]);
<div ng-controller="logout">
    <p>{{notification.text}}</p>
    <button ng-repeat="button in notification.buttons" ng-click="button.fn()"> {{button.label}} {{button.fn}}</button>
    <button ng-click="logout()"> Test</button>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!