调用Angular嵌套函数

时间:2016-11-15 14:04:20

标签: javascript angularjs

我正在尝试在Angular中调用嵌套函数。我已经以这种方式格式化函数以便代理代码,但是当通过ng-click调用函数时,它似乎无法工作。

在我的情况下,由于变量名由本地范围占用,因此发生范围冲突,因此我命名了一个控制器并将其作为控制器的子属性调用,但没有成功。

我已经创建了一个jsfiddle来演示我的意思: https://jsfiddle.net/838L40hf/16/

HTML:

<div class="InviteAppContainer" ng-app="InviteApp">
    <div ng-controller="InviteController as cntrl">
      <button ng-click="alert()">
        Alert, standard
      </button>

      <div ng-repeat="invite in invites">
        <button ng-click="cntrl.invite.alert(invite.name)">
          Alert, {{invite.name}}
        </button>
      </div>
    </div>
</div>

JS:

var InviteApp = angular.module('InviteApp',[])
.controller('InviteController', function($scope) {
    $scope.invites = {
    0 : {
        "name":"invite 1",
        }, 
    1 :{
        "name" : "invite 2"
        }
  };

    $scope.invite = {
    alert : function(name) {
            alert(name);
    }
  };

    $scope.alert = function() {
        alert("alert2!");
    };
});

3 个答案:

答案 0 :(得分:3)

如果您使用controller as语法,如果您希望通过别名控制器名称访问它们,则应该将内容绑定到this而不是$scope

只需将绑定从$scope.invite更改为this.invite即可。

https://jsfiddle.net/pL4wc10n/

答案 1 :(得分:1)

您应该使用this

<强>的Javascript

var InviteApp = angular.module('InviteApp',[])
  .controller('InviteController', function($scope) {
    // controllerAs : cntrl
    var that = this;

    $scope.invites = {
     0 : {
      "name":"invite 1",
     }, 
     1 :{
      "name" : "invite 2"
     }
    };
    // USING THIS you have cntrl.function
    that.invite = {
     alert : function(name) {
      alert(name);
    }
  };

  $scope.alert = function() {
    alert("alert2!");
  };
});

答案 2 :(得分:0)

&#13;
&#13;
var InviteApp = angular.module('InviteApp',[])
.controller('InviteController', function($scope) {
	$scope.invites = {
  	0 : {
    	"name":"invite 1",
		}, 
    1 :{
    	"name" : "invite 2"
		}
  };

	$scope.invite = {
  	alert : function(name) {
			alert(name);
  	}
  };

	$scope.alert = function() {
		alert("alert2!");
	};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="InviteAppContainer" ng-app="InviteApp">
  	<div ng-controller="InviteController as cntrl">
      <button ng-click="alert()">
        Alert, standard
      </button>
      
      <div ng-repeat="i in invites">
        <button ng-click="invite.alert(i.name)">
          Alert, {{i.name}}
        </button>
      </div>
    </div>
</div>
&#13;
&#13;
&#13;

我编辑的内容:

<div ng-repeat="i in invites">
    <button ng-click="invite.alert(i.name)">
        Alert, {{i.name}}
    </button>
</div>
相关问题