AngularJS:从html ng-click调用工厂中的函数

时间:2016-06-22 11:12:25

标签: javascript html angularjs

我试图在html中调用一个在工厂中声明的函数(myfunc):

<button type="button" class="btn btn-default btn-sm" ng-click="myfunc(search_name)">Search</button>

控制器和工厂代码如下:

var angularjsapp = angular.module('graphApp', ['ngAnimate', 'ui.bootstrap']);
angularjsapp.factory('searchFactory', function() {
      //return $resource('friends.json');
      return{
            myfunc:function(search_name){
                console.log('ok')
                keyword_type = 1
                WebSocketTest(search_name,keyword_type)

                }
            }   
    });

angularjsapp.controller('AccordionDemoCtrl', function($scope,searchFactory) {
    $scope.count = 0;
    $scope.namesPerPage = 10
    $scope.currentPage = 1;
    $scope.searchFactory = searchFactory.myfunc 
});

到目前为止,我无法在控制台中记录'ok'

3 个答案:

答案 0 :(得分:1)

您应该像这样调用分配给scope的{​​{1}}函数:

searchFactory.myfunc

答案 1 :(得分:1)

您需要在searchFactory变量

中存储$scope.searchFactory的引用
$scope.searchFactory = searchFactory;

而不是

$scope.searchFactory = searchFactory.myfunc;

OR ,在myfunc

中将set变量用作scope
$scope.myfunc = searchFactory.myfunc;

而不是

$scope.searchFactory = searchFactory.myfunc;

答案 2 :(得分:0)

而不是:

$scope.searchFactory = searchFactory.myfunc

做类似的事情:

$scope.myfunc = function(arg) {
    searchFactory.myfunc(arg);
}

然后,将search_name中的ng-click="myfunc(search_name)"定义为模型:

<input ng-model="search_name">

或范围:

$scope.search_name = "Nicholas";