简体   繁体   中英

Why Are My Object's Properties Being Overwritten?

I have the following code in Angular, which is an attempt to allow for multiple instances of the same Controller on the same web page. The problem is, every time a new instance is created, it adds itself to the instance object, but erases the other properties (ie, instances) on the instance object. I think this is a simple javascript syntax problem unrelated to Angular, but I can't figure it out. Any advice?

angular.module('mean.root').controller('ContentA1Controller', ['$scope', '$location', 'Global', 'Data', '$timeout', '$interval', 'Clients', 'Modals', '$element', function ($scope, $location, Global, Data, $timeout, $interval, Clients, Modals, $element) {

            // Defaults
            $scope.instances = { A: {}, B: {}, C: {}, D: {}, E: {}, F: {} };

            // Methods
            $scope.createNewInstance = function() {
                var instance = $($element).closest('.content-container').attr('id');
                // Add ID to content
                $($element).find('.content').attr( "id", "contentA1instance"+instance );
                Data.priceByDay(function(prices){
                    // Load Chart Data
                    $scope.instances[instance].data = [1,2,3,4,5];
                    // Log Instance Object
                    console.log($scope.instances);

So, when I add one instance to the controller, it works and I log:

$scope.instances = { A: { data: [1,2,3,4,5] }, B: {}, C: {}, D: {}, E: {}, F: {} }

Then when I add another instance, running the createNewInstance() method again, it will log:

$scope.instances = { A: {}, B: { data: [1,2,3,4,5] }, C: {}, D: {}, E: {}, F: {} }

我建议为每个实例使用不同的控制器并在$ rootScope中保留共享数据,或者更好地为整个页面使用一个控制器并让每个实例仅在一个映射项上运行。

var instance = $($element).closest('.content-container').attr('id');
....
$scope.instances[instance].data = [1,2,3,4,5];

it's choosing the id of the closest .content-container to the element where the controller is bound in the page. Since you said you've used the controller twice, one of those bindings is closer to .content-container#A and one is closer to .content-container#B . This looks like the code is "working as designed" but you may not have "designed what you meant".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM