0

I am having function in my controller.

$scope.TestFn = {
            func1: function() {
                console.log('in function TestFn func1')             
                },
            func2: function() {
                console.log('in function TestFn func2')             
                }   
        }

That i am calling in my directive as below,

<div ng-init="TestFn.func1()"><div>

This is working fine. What i want to know, what do we call this kind of functions arrangements. Like we are grouping relevant functions all together. And is it possible to have same way for declaring variables. For example,

$scope.Test.variable1 = 'value1';
$scope.Test.variable2 = 'value2';

Which i can use like {{Test.variable1}} or {{Test.variable2}} It is essential for me to know because i am having many html template and want to keep all relevant functions and variables all together for easier management.

Thanks

3
  • do your templates have different controllers? You might want a controllerAs syntax: ng-controller="TestCtrl as Test", and then call scoped variables with {{Test.variable1}} Commented Apr 18, 2018 at 10:55
  • All templates are in same controller. Commented Apr 18, 2018 at 10:58
  • I think you up-voted my answer. If you think it clarifies things for you, perhaps you'd consider marking it as the correct answer? Commented Apr 18, 2018 at 13:06

1 Answer 1

1

Not sure why you have doubts about this, but if you read the Angular documentation you'll see that both assigning variables and functions to $scope is just about the most basic standard thing you'd be expected to do do with a Scope object.

angular.module('scopeExample', [])
.controller('MyController', ['$scope', function($scope) {
    $scope.username = 'World';

    $scope.sayHello = function() {
        $scope.greeting = 'Hello ' + $scope.username + '!';
    };
}]);

In the above example notice that the MyController assigns 'World' to the username property of the scope.

...

Similarly the controller can assign behavior to scope as seen by the sayHello method, which is invoked when the user clicks on the 'greet' button.

So yes, you can assign variables as well as functions. It's what the scope is there for.

And no, there's no specific name for referring to functions in a map -which is what you're basically doing in your code sample. The $scope object can hold variables and functions structured in maps and arrays -or combinations of both.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for explanation. It gave me a lead to store all the variables in array form.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.