数据绑定控制器 - 服务:为工作对象,但不换号但不、绑定、控制器、对象

2023-09-13 05:09:57 作者:生活就要屁颠屁颠得过

为什么在 json_var 同步为 INT 而不是为 INT数据

Why are the data synced for the int in json_var and not for the int?

myService.json_var $ scope.json_var 更改进行更新。 myService.int_var 不更新时, $ scope.int_var 的变化。

myService.json_var is updated when $scope.json_var changes. myService.int_var is not updated when $scope.int_var changes.

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

myApp.factory('myService', [
  function() {
     return {
        json_var : {val:17},
        int_var : 36
     }

     }
  ]);


myApp.controller('myCtrl', [ '$scope',  'myService', 
  function ($scope, myService)
  {
     $scope.json_var = myService.json_var; // doing this myService.json_var is updated when $scope.json_var changes
     $scope.int_var = myService.int_var; // no sync for int

     $scope.deb = function()
     {
        console.log($scope.int_var);
        console.log( myService.int_var);

        console.log($scope.json_var.val);
        console.log( myService.json_var.val);
     }
  }
] );

https://gist.github.com/SebSept/8ddcaad130ef9c091bd0

推荐答案

在JavaScript中,复合类型(对象,数组)按引用传递(参考副本,是precise)和原语(字符串,数字,布尔值)是按值传递。

In JavaScript, composite types (objects, arrays) are passed by reference (copy of a reference, to be precise), and primitives (strings, numbers, booleans) are passed by value.

36 是一种原始。当你通过从​​你的服务原语( myService.int_var )到您的控制器( $ scope.int_var )的 36 是按值传递。当您更改 $ scope.int_var 42 myService.int_var 变量将不会反映这种变化(这是每个语言设计)。

36 is a primitive. When you pass your primitive from your service (myService.int_var) into your controller ($scope.int_var) the 36 is passed by value. When you change $scope.int_var to 42 the myService.int_var variable will not reflect the change (this is per language design).

在另一方面, myService.json_var 是一个复合材料。当你通过 myService.json_var $ scope.json_var ,到为myService的参考。 json_var 对象是以值到 $ scope.json_var 变量传递。当您更改变量中的东西(例如,如果你改变 json_var.val 18 )的变化将反映在 myService.json_var 对象内为好,这样 myService.json_var.val 将等于 18 以及

On the other hand, myService.json_var is a composite. When you pass myService.json_var to $scope.json_var, a reference to the myService.json_var object is passed by value to the $scope.json_var variable. When you change something inside that variable (e.g. if you change json_var.val to 18), the change will be reflected inside the myService.json_var object as well, so myService.json_var.val will equal 18 as well.

TL;博士确保总有一个点。某个地方,当你身边路过的东西角。

tl;dr Make sure there's always a dot "." somewhere when you're passing things around in Angular.