是否可以编写这样的函数?
$scope.myFunc = function () {
this.details = 1;
this.setDetails = function (d) {
this.details = d;
}
}
如何从视图中调用此函数?
<a href="javascript:void(0)" ng-click="myFunc.setDetails('hi')">set Details</a>
它甚至没有调用我的功能。
答案 0 :(得分:1)
我为你准备好工作实例。首先使用构造函数,然后通过调用$scope.myfunc
创建新实例new MyFunc()
。
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope) {
//Constructor function
function MyFunc () {
this.details = 1;
this.setDetails = function(details) {
this.details = details;
}
}
//New instance of MyFunc
$scope.myfunc = new MyFunc();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myController">
<input type="text" ng-model="myfunc.details">
<button ng-click="myfunc.setDetails('hi')">Click me</button>
</div>
</div>
&#13;