handsome
handsome

Reputation: 2402

angularJS send parameter from template to controller

I want to do something like this

<div ng-controller="test" init="category = 1">
...
</div>

and in my controller

var myApp = angular.module('myApp',[]);
myApp.controller('test', ['$scope, $http', function($scope, $http) {
    $http.get('/categories' + $scope.category...
}]);

but it doesn´t work like that. any ideas on how to pass a parameter from the template to the controller definition? thank you.

Upvotes: 1

Views: 41

Answers (3)

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5674

The directive is called ngInit, so to use it correctly you'd do it like this:

<div ng-controller="test" ng-init="category = 1">
...
</div>

Using ngInit for initialization can be considered an anti-pattern according to the documentation, except for certain specific use cases. You mention passing data from PHP to Angular, which is an acceptable use case, but I would probably consider a different solution to avoid ngInit:

<script>
    angular.module('myApp').constant('MY_DATA', {
        category: 1
    });
</script>

You just add this to your PHP page somewhere after you load in your angular application. Then you can inject MY_DATA into your controller:

angular.module('myApp').controller('test', ['MY_DATA', function (MY_DATA) {
    $http.get('/categories' + MY_DATA.category);
}]);

Upvotes: 1

AlexanderDrysdale
AlexanderDrysdale

Reputation: 64

I'd suggest the following:

<div ng-controller="test" init="init(1)"></div>

controller:

$scope.category = 0;

$scope.init = function(myCategory){ 
   $scope.category = myCategory;
   $scope.callGetFunction(); //$http.get('/categories' + $scope.category...
}

Upvotes: 0

Rahul Sharma
Rahul Sharma

Reputation: 10071

Try this, hope it'll solve your problem.

HTML CODE

<div ng-controller="test" init="init(1)">

CONTROLLER CODE

var myApp = angular.module('myApp', []);
myApp.controller('test', ['$scope, $http', function ($scope, $http) {
    $scope.init = function (category) {
        $http.get('/categories' + category);
    }
}]);

Upvotes: 2

Related Questions