简体   繁体   中英

Angular controller function is not recognized in CoffeeScript

I am fairly new to Angular + CoffeeScript and am using it for a Rails project. I am trying to create a function in the controller, which runs if I hit a button in a view.

This is the html

<div id="labs">
  <div class="clients" ng-repeat="client in clients" ng-class="{first: $index == 0}">
    <h1>{{client.name}}</h1>
    <div class="labs">
      <ul>
        <li ng-repeat="lab in client.labs">
          <a ng-href="/#!/labs/{{lab.id}}/process">
            <button ng-click = "test()">Test</button>
            <span>{{lab.name}}</span>
            <span>{{lab.created_at | date:'MMMM yyyy' }}</span>
          </a>
        </li>
      </ul>
    </div>
  </div>
</div>

This is the Controller

angular.module("deloitte").controller('labsCtrl', ['$scope', 'labService','labPreferencesService', ($scope, labService, labPreferencesService ) ->  

  labService.query (data) ->
    $scope.clients = data
   # console.print (clients)

       $scope.test -> console.log("Hello!");
])

And this is the error

angular.js?body=1:5755 TypeError: $scope.test is not a function
    at new <anonymous> (labsController.js?body=1:7)
    at invoke (angular.js?body=1:2903)
    at Object.instantiate (angular.js?body=1:2915)
    at angular.js?body=1:4806
    at update (angular.js?body=1:14199)
    at Object.Scope.$broadcast (angular.js?body=1:8308)
    at angular.js?body=1:7464
    at wrappedCallback (angular.js?body=1:6847)
    at wrappedCallback (angular.js?body=1:6847)
    at angular.js?body=1:6884

I looked up the syntax and it seems correct . Doing =-> throws an error too. Help would be appreciated

Do you want to call .test() function on your $scope or define it?

$scope.test -> console.log("Hello!");

// Generates
$scope.test(function() {
  return console.log("Hello!");
});

If you want to define/assign:

$scope.test = -> console.log("Hello!");

// Generates
$scope.test = function() {
  return console.log("Hello!");
};

and that's probably what you want.

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