javascript - angularjs 注入的疑问

 文弱书生_李 发布于 2022-11-20 03:37
var appModule = angular.module('app', []);
appModule.directive('hello',["$scope","custom", function($scope,custom) {
    return {
        restrict: 'E',
        template: '

Hi there

', replace: true }; });
var appModule = angular.module('app', []);
appModule.directive('hello',["$scope","custom", function($scope,custom) {
    return {
        restrict: 'E',
        template: '

Hi there

', replace: true }; });
var appModule = angular.module('app', [$scope","custom"]);

这分别是 指令注入,控制器注入,模块中注入,那么在angular 中注入的区别是什么?为什么要分这么多中类型?!

2 个回答
  • a.directive("expender",["$scope",function($scope){

    return{
        restrict:"EA",
        replace:true,
        transclude:true,
        scope:{
            title:"=expenderTitle",
        },
        template:'<p>'+
            '<p class="title" ng-click="toggle()">{{title}}</p>'+
            '<p class="body" ng-show="ShowMe" ng-transclude></p>'+
            '</p>',
        link:function (scope,element,attrs){
            scope.showMe=false;
            scope.toggle=function (){
                scope.showMe=!scope.showMe;
                console.log(scope.showMe);
            }
        }
    }

    }])
    但是指令这样写会报错?!

    2022-11-20 04:06 回答
  • 首先,修改一下自己的代码吧,什么叫模块中注入(怎么还有这种说法),是加入模块依赖吧。况且本身你的写法就是错的。请自行修改好。

    第二,你得先了解什么是依赖注入(DI),如果玩过Java的Spring,对这个就不会陌生,说白了就是一种设计模式,让代码管理你的依赖。

    这里给你两个参考资料: (最好翻墙将第二个视频看了,会对angular为什么用DI有个深入的了解)
    http://docs.ngnice.com/guide/di
    https://www.youtube.com/watch?v=_OGGsf1ZXMs&list=PLw5h0DiJ-9PB-vLe3vaNFLG-cTw0Wo7fw&index=1

    第三,你说得在控制器中注入和在指令中注入是没有区别的,模块那个不叫依赖注入。

    依赖注入分为两部分:

    • 在哪里注入: 有controller, directive, factory, service, provider,config, run, filter

    • 什么可以被注入: factory, service, provider, constant, value

    主要区别看下图(配置阶段为config方法,run为运行阶段,没提到的,正常使用就OK)

    2022-11-20 04:06 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有