1

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.

2
  • why you want to pass through HTML, If you can directly pass from the controller? Commented Mar 5, 2018 at 7:14
  • because I´m using angularJS with PHP and the I´m using the same angularJS controller in multiple pages. I need a way to pass a parameter from PHP to the angularJS controller to make the appropriate $http call. Commented Mar 5, 2018 at 7:20

3 Answers 3

2

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);
    }
}]);
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}]);

1 Comment

It's particularly useful if you're initializing multiple values from server side scripting, since initializing multiple values through ngInit quickly becomes difficult to read.
0

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...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.