这个简单程序的输出是什么,为什么?

时间:2018-09-04 17:58:42

标签: angularjs angularjs-directive

<div ng-app="myApp">
    <div w3-test-directive></div>
    <div w3-test-directivee ></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>

<script>
    var app = angular.module("myApp", []);
    app.directive("w3TestDirective", function() {
        return {
            template : "howw!"
        };
    });
</script>
<script>
    var app = angular.module("myApp", []);
    app.directive("w3TestDirectivee", function() {
        return {
            template : "hie how are you!"
        };
    });
</script>

将返回哪个模板?我有两个脚本:将调用哪个脚本,为什么?

2 个答案:

答案 0 :(得分:0)

在第二个If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. 调用中删除第二个参数,它将按预期工作。有关第二个参数,请参见docs

myApp

由于您提供了第二个参数,所以每次覆盖之前定义的内容时,都会创建一个新的<div ng-app="myApp"> <div w3-test-directive></div> <div w3-test-directivee ></div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script> <script> var app = angular.module("myApp", []); app.directive("w3TestDirective", function() { return { template : "howw!" }; }); </script> <script> var app = angular.module("myApp"); app.directive("w3TestDirectivee", function() { return { template : "hie how are you!" }; }); </script>模块。

{{1}}

答案 1 :(得分:0)

删除应用模块的多重定义,即删除定义应用的第一个指令。

<div ng-app="myApp">
    <div w3-test-directive></div>
    <div w3-test-directivee></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>

<script>
    var app = angular.module("myApp", []);
    app.directive("w3TestDirective", function () {
        alert("w3TestDirective called");
        return {
            template: "howw!"
        };
    });
</script>
<script>
   // var app = angular.module("myApp", []);
    app.directive("w3TestDirectivee", function () {
        alert("w3TestDirectivee called");
        return {
            template: "hie how are you!"
        };
    });
</script>