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

Javascript 第一次编写Angular指令并返回编译后的模板,javascript,angularjs,Javascript,Angularjs,我正试图写我的第一个指令,有点困惑。我想返回一个编译过的模板,其中ng click是有效的。我有: var arcModule=angular.module('Octo',[]); 控制器('MainCtrl',函数($scope,$http){ $scope.sayHello=function(){ 警惕(“你好”); } }); Octo.指令('myCustomer',函数(){ 返回{ 模板:“姓名:打招呼地址:” }; }); 在我的plnkr中,为什么没有输出我的客户指令 但对

我正试图写我的第一个指令,有点困惑。我想返回一个编译过的模板,其中ng click是有效的。我有:

var arcModule=angular.module('Octo',[]);
控制器('MainCtrl',函数($scope,$http){
$scope.sayHello=function(){
警惕(“你好”);
}
});  
Octo.指令('myCustomer',函数(){
返回{
模板:“姓名:打招呼地址:”
};
});
在我的plnkr中,为什么没有输出我的客户指令

但对于下一步是什么,我有点不知所措。我有点了解链接和编译的概念,但不确定如何实现。我怎么能这样做?医生就像糖蜜,我觉得我所做的是难以置信的简单


thx对于任何帮助

您遇到的问题,上面的代码中不清楚的是您正在覆盖定义了单击功能的控制器

您在代码中有两次这样做:
arcModule.controller('MainCtrl',function($scope){

我所做的一切就是删除第二个控制器定义,以便使用第一个带有click函数的控制器(您确实需要将它们组合起来)。然后将
添加到DOM中。该指令插入并添加了指令标记,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>
var arcModule=angular.module('Octo',[]);
控制器('MainCtrl',函数($scope,$http){
$scope.sayHello=function(){
警惕(“你好”);
}
$scope.customer={
名字:“娜奥米”,
地址:“1600圆形剧场”
};
});  
指令('myCustomer',函数(){
返回{
模板:“名称:{{customer.Name}}单击以打招呼。地址:{{customer.Address}”
};
});
标记:

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>


看起来您实际上并没有在标记中的任何地方使用您的指令。thx@Zajn不应该调用它吗?我觉得我的简单指令中可能有语法错误,因为第一次ng单击不起作用。我知道指令很关键,所以我只需尽可能地向它们公开自己。是的,这会发生至少要让它显示出来。当我加载你的plunkr时,我没有看到任何地方。我想m59回答了你的问题!是的,我想他回答了。首先使用plunkr也有很多活动部件。thx寻求帮助。thx@m59,那么该模板会被认为是编译的吗?我会这样认为,因为它只是在第一次加载时被渲染出来的装载(如果
compiled
仅对写入dom.Thx的新html有意义,则可能没有。@timpone是的,它已编译。如果不是,数据绑定将无法工作。
template
参数自动编译,当然编译函数也是如此。如果使用链接函数添加标记,则y你必须手工编译。