Angular.js 依赖注入问题
高洛峰
高洛峰 2017-05-15 17:03:14
0
2
589
//定义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>

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

这是为什么???
控制器之间可以进行依赖注入吗???

A.value是什么???

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
黄舟

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;
});
给我你的怀抱

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!