service portals

vodnalar26
Tera Contributor

hello everyone,

When to use c. and $scope in service portals scripting?

9 REPLIES 9

SamSundar
Tera Contributor

In ServiceNow Service Portal, c and $scope serve different purposes and are used in different scenarios.

Use c (Controller)

  • c is the controller object (var c = this;) and is the recommended way to expose data and functions to your widget's HTML.

  • Use it for:

    • Binding data to the UI ({{c.variable}})

    • Handling button clicks and other user interactions

    • Calling server scripts using c.server.get(), c.server.update(), or c.server.refresh()

    • Storing widget state and client-side logic

Example:

api.controller = function() {
    var c = this;

    c.message = "Hello Service Portal";

    c.sayHello = function() {
        alert(c.message);
    };
};

Use $scope

  • $scope is part of AngularJS and is mainly used for Angular-specific features rather than general widget development.

  • Common use cases include:

    • Listening for events using $scope.$on()

    • Broadcasting or emitting events using $scope.$broadcast() and $scope.$emit()

    • Watching variables with $scope.$watch()

    • Integrating with Angular directives or legacy Angular code that depends on $scope

Example:

api.controller = function($scope) {
    var c = this;

    $scope.$on('sp.page.loaded', function() {
        console.log('Page loaded');
    });
};

Ankur Bawiskar
Tera Patron

@vodnalar26 

my thoughts

-> use c (or this) for most Service Portal widget client scripting as the widget's controller reference

-> use $scope when you need Angular scope features (watching, broadcasting, or accessing parent/root scopes) or when interacting with other widgets via $rootScope events

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  10x ServiceNow MVP  ||  ServiceNow Community Leader

yashkamde
Giga Sage

Hello @vodnalar26 ,

 

c. - use for almost all standard widget development, as it isolates widget data.

  • Use c.data to pass data between your Client Script and Server Script
  • Access widget properties in your HTML Template using c.data {{c.data.myVariable}}
  • Call built-in server methods like c.server.update() or c.server.get().

$scope  - primarily for AngularJS-specific features that the controller alone cannot handle .

 

Refer this for detailed understanding :

$scope in service portal widget 

 

If my response helped mark as helpful and accept the solution.

Aditya_hublikar
Giga Sage

Hello @vodnalar26 ,

 

Refer this it will help you :

https://www.servicenow.com/community/developer-forum/in-service-portal-widgets-why-do-we-use-the-c-v...

 

If this helps you then mark it as helpful and accept as solution.

Regards,

Aditya