我可以在angularjs的$ scope函数中编写这个函数吗?

时间:2015-10-17 14:06:14

标签: javascript angularjs

是否可以编写这样的函数?

$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>

它甚至没有调用我的功能。

1 个答案:

答案 0 :(得分:1)

我为你准备好工作实例。首先使用构造函数,然后通过调用$scope.myfunc创建新实例new MyFunc()

&#13;
&#13;
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;
&#13;
&#13;