访问一个angularjs控制器中的本地函数

时间:2018-06-04 07:25:14

标签: javascript angularjs

我对angularjs和javascript非常新。我有一个像这样的工作代码:

my_ctrl.js

app.controller('my_ctrl', function($scope, $filter, $http) {
    $scope.getmymodel = function(){$http({
        method: 'GET',
        url: '/getmymodel',
        headers: {'Content-Type': 'application/json'}
        }).then(function(response){$scope.getmymodel=response.data;});};
    $scope.getmymodel();
});

HTML:

<div ng-controller="my_ctrl as ctrl" ng-cloak>
<table class="table table-striped table-hover table-condensed">
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="model in getmymodel">
            <td>{{model.name}}</td>
        </tr>
    </tbody>
</table>
</div>

我想在HTML中使用控制器调用js函数,并使函数调用本地控制器。我修改了下面的代码,但没有运气。任何帮助表示赞赏!

my_ctrl.js

app.controller('my_ctrl', function($scope, $filter, $http) {
    this.getmymodel = function(){$http({
        method: 'GET',
        url: '/getmymodel',
        headers: {'Content-Type': 'application/json'}
        }).then(function(response){this.getmymodel=response.data;});};
    this.getmymodel();
});

HTML:

<div ng-controller="my_ctrl as ctrl" ng-cloak>
<table class="table table-striped table-hover table-condensed">
    <thead>
        <tr>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="model in ctrl.getmymodel">
            <td>{{model.name}}</td>
        </tr>
    </tbody>
</table>
</div>

1 个答案:

答案 0 :(得分:1)

将此分配给变量,如

var vm = this;
控制器中的

并定义类似

的功能
vm.getmymodel = function(){};

和HTML

<div ng-controller="my_ctrl as vm">
   ...
   and call function 

   <tr ng-repeat="model in vm.getmymodel">
      <td>{{model.name}}</td>
   </tr>

   ...
</div>