search

Home  >  Q&A  >  body text

Angular.js dependency injection issues

//定义A模块

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

A.value('time',new Date());

//定义B模块

var B = angular.module('b',['a']);

B.controller('conB',function($scope,time){
    $scope.b = time.getFullYear();
});


<p ng-controller = "conB">
    {{b}} //--> 2016
</p>



————————————————————————————————————————

    //定义A模块

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

A.controller('conA',function($scope){
    $scope.a = 12;
});

//定义B模块

var B = angular.module('b',['a']);

B.controller('conB',function($scope,conA){
    $scope.b = conA.a;
});


<p ng-controller = "conB">
    {{b}} //--> {{b}}报错
</p>

————————————————————————————————————————

Why is this???
Can dependency injection be performed between controllers???

What is A.value???

高洛峰高洛峰2821 days ago628

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-15 17:05:14

    value很像是个常量(除了不能在config stage use), see the documentation:

    As for why the way conA不能在conB中使用的问题,纯粹是你玩错了路子,首先,这种controller depends on each other is not recommended; secondly, if you insist on playing like this, the code is not written like that:

    //定义B模块
    
    var B = angular.module('b',['a']);
    
    B.controller('conB',function($scope, $controller){
        var ctrlAViewModel = $scope.$new();
        $controller('conA',{$scope : ctrlAViewModel });
        $scope.b = ctrlAViewModel.a;
    });

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-15 17:05:14

    A brief description of the mobile phone used:

    var B = angular.module('b',['a'])
    This means that module B depends on module A, and then

    B.controller('conB',function($scope,time){ $scope.b = time.getFullYear(); });

    That is to say, time is injected into the Conteoller of module B. If injected in this way, the class to be injected must be the same as the definition. If you want to use the second method, that is, if you write the following, you can use $inject, which can also avoid the problem of compressing code variable abbreviations.

    reply
    0
  • Cancelreply