简体   繁体   中英

How to call a custom function from html with angularjs?

I'd like to define separate methods within my js controllers as follows:

    angular.module('test').controller('mycontroller', mycontroller);
    function mycontroller() {
        //do sth
    };

    function test(value) {
        console.log(value); //this is never written
    };

This way I'd have a clean structure and each method separated in its own block.

But when I try to use it as follows, there is not output.

<div ng-controller='mycontroller'>
    {{test('printme')}}
</div>

Why?

Try putting your test function inside your controller, and change it to

$scope.test = function(value){
    console.log(value)
};

Also add $scope dependency to your controller

If you want to keep you files looking clean you can follow John Papa's style guide: https://github.com/johnpapa/angular-styleguide

Here is how I fixed your question and applied a clean approach to it: http://plnkr.co/edit/tYYvssVWUfvHyXE8ilD8?p=preview

angular.module('testApp', [])
  .controller('ctrl', ctrl);

function ctrl($scope) {
  /* -- Public Properties & Methods -- */

  $scope.test = test;


  /* -- Private Properties & Methods -- */

  function test(value) {
    console.log(value);
  }
}

Because my code is in an IIFE, you can actually have that function test anywhere inside of that block, instead of having it inside the controller function:

angular.module('testApp', [])
  .controller('ctrl', ctrl);

function ctrl($scope) {
  /* -- Public Properties & Methods -- */

  $scope.test = test; 
}

/* -- Private Properties & Methods -- */
function test(value) {
    console.log(value);
}

http://plnkr.co/edit/VXbOuOvHaIhRFBVZD16p?p=preview

I just had a thought about doing this according to the second way. A fair amount of times we create variables we wish to bind to the DOM: $scope.showOptions . If we have the function outside of the controller we no longer have access to this $scope.showOptions so you would have "difficulty" interrogating it. You could easily get around this by either requesting the variables/scope through the function parameter. Or creating a small wrapper function that will dispatch out (almost like double dispatching).

$scope.test = function test() { testImpl($scope.showOptions); };

function testImpl(showOptions) {
    console.log(showOptions);
}

This will allow you to keep all of your main heavy lifting outside the controller but does introduce a new layer of complexity, one which I know I could certainly do without.

So the choice is yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM