gpt4 book ai didi

angularjs - 使用路由时指令不起作用

转载 作者:行者123 更新时间:2023-12-01 13:38:42 24 4
gpt4 key购买 nike

看下面的 AngularJS 代码

dir.js

(function() {
var myApp = angular.module("MyApp");
myApp.directive('myMovie', function() {
return {
restrict: 'E',
transclude: 'true',
template: '<h1>This is my first directives</h1>',
link: function(scope, element, attr){
element.append("<strong>"+attr.title+"</strong>");
}
};
});

})();

当我使用 Angular 路由时,上面的指令不起作用。相同的代码在我的应用程序中不使用路由也能工作。该怎么办?有没有什么想法为什么当我在我的应用程序中使用“ngRoute”时这段代码不起作用?

我已将 “myMovie”标签 添加到 HTML 正文中。仍然没有在 HTML 页面上获取指令模板。

下面是我的“ngRoute”代码

script.js

(function(){
var app = angular.module("MyApp", ["ngRoute"]);

app.config(function($routeProvider){
$routeProvider
.when("/", {
templateUrl : "main.html",
controller : "Main",
controllerAs : "vm"
})
.when("/first", {
templateUrl : "first.html",
controller : "First",
controllerAs : "vm"
})
.when("/second", {
templateUrl : "second.html",
controller : "Second",
controllerAs : "vm"
})
.otherwise(({
templateUrl : "404.html"
}));
});



})();

first.controller.js

(function(){
var app = angular.module("MyApp");
app.controller("First", ["$scope", function($scope){
var vm = this;
vm.message = "This is first page";
}]);
})();

second.controller.js

(function(){
var app = angular.module("MyApp");
app.controller("Second",["$scope", function($scope){
var vm = this;
vm.message = "This is second page";
}]);
})();

ma​​in.controller.js

(function(){
var app = angular.module("MyApp");
app.controller("Main", ["$scope", function($scope){
var vm = this;
vm.message = "This is main page";
}]);

})();

我使用指令的 HTML 页面

first.html

<div>
<myMovie></myMovie>
</div>

我在上面的代码哪里错了?..

最佳答案

AngularJS normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

myMovie 指令将与 my-movie 标签一起使用。

按照惯例,我建议您使用连字符 (-) 作为限制符,但您也可以使用 :_

Working demo

Source

关于angularjs - 使用路由时指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49238267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com