gpt4 book ai didi

javascript - 第一次编写 Angular 指令并返回编译后的模板

转载 作者:行者123 更新时间:2023-12-02 17:59:20 24 4
gpt4 key购买 nike

我正在尝试编写我的第一个指令,但有点困惑。我想返回一个已编译的模板,其中 ng-click 起作用。我有(http://plnkr.co/edit/gr3ha1lxgcFp3z4L148S?p=preview):

var arcModule=angular.module('Octo', []);


arcModule.controller('MainCtrl', function($scope, $http){

$scope.sayHello=function(){
alert("hello");
}
});

Octo.directive('myCustomer', function() {
return {
template: 'Name: <div ng-click="sayHello()">say hello</div> Address: '
};
});

在我的plnkr中,为什么没有输出my-customer指令?

但我有点不知道下一步是什么。我有点了解链接和编译的概念,但不知道如何实现。我怎么能这样做呢?这些文档就像糖蜜一样,我觉得我所做的非常简单。

感谢您的帮助

最佳答案

您遇到的问题(在上面的代码中不清楚)是您正在覆盖定义了单击函数的 Controller 。

您的代码中出现了两次:arcModule.controller('MainCtrl', function($scope) {

为了使您的指令工作,我所做的就是删除第二个 Controller 定义,以便使用第一个具有单击功能的 Controller 定义(您实际上只需将它们组合起来即可)。然后添加<div my-customer></div>到 DOM。该指令启动并添加了指令标记,并且单击功能正常工作。

这是更正后的完整代码:Live demo (click).

JavaScript:

var arcModule=angular.module('Octo', []);

arcModule.controller('MainCtrl', function($scope, $http){
$scope.sayHello=function(){
alert("hello");
}
$scope.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
});

arcModule.directive('myCustomer', function() {
return {
template: 'Name: {{customer.name}}<button ng-click="sayHello()">Click to say hello.</button> Address: {{customer.address}}'
};
});

标记:

<body ng-app="Octo" ng-controller="MainCtrl">
<div my-customer></div>

关于javascript - 第一次编写 Angular 指令并返回编译后的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20695286/

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