0

I've just started with ngJS.

I've found the way to bind the service objects to controllers.

I would like to know that, is this the good practice to achieve this or there is a recommended way to do this?

I would also like to know why is this possible only on objects and not properties?

Here's my fiddle. In depth explanations are welcome.

Thanks.

Mehulkumar
  • 836
  • 2
  • 10
  • 23

2 Answers2

1

Read this SO thread.

A variable can hold one of two types of values: primitive values and reference values.

  • Primitive values are data that are stored on the stack.
  • Primitive value is stored directly in the location that the variable accesses.
  • Reference values are objects that are stored in the heap.
  • Reference value stored in the variable location is a pointer to a location in memory where the object is stored.
  • Primitive types inlcude Undefined, Null, Boolean, Number, or String.

The basics

Objects are aggregations of properties. A property can reference an object or a primitive. Primitives are values, they have no properties.

JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

Community
  • 1
  • 1
Praveen Prasannan
  • 7,093
  • 10
  • 50
  • 70
0

Actually, you bound only scope properties to the view and then these properties have been initialized with service properties values. Your code with some edits:

var myApp = angular.module('myApp', []);

myApp.service('s1', function() {
    this.Input = {
        name: 'John'
    };

    this.name = 'Doe';
});

myApp.controller('c1', function($scope, s1) {
    $scope.Input = s1.Input;
    $scope.name = s1.name;
});

myApp.controller('c2', function($scope, s1) {
    $scope.Input = s1.Input;
    $scope.name = s1.name;

    $scope.change = function() {
        console.log("s1.name = "+s1.name);
        s1.name = "ciao";
        console.log("s1.name = "+s1.name);
    };
});

So if you change the value of $scope.name of the c2 controller (for example editing the input box in the view) that doesn't propagate to s1.name. And more, if you change the s1.name property (see $scope.change method in c2 controller) this modification is not propagated to $scope.name.

A way to propagate changes in service properties is using events, that is rising events from service and listening the same events in the controllers (see How do I create a custom event in an AngularJs service).

Here is the jsfiddle updated: http://jsfiddle.net/0j0mdjco/2/

Community
  • 1
  • 1
beaver
  • 17,333
  • 2
  • 40
  • 66