第一次写一个角指令和返回编译模板 [英] first time writing an Angular directives and returning a compiled template

查看:121
本文介绍了第一次写一个角指令和返回编译模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写我的第一个指令,并有点糊涂。我想返回编译模板,其中NG-点击是功能性的。我有( http://plnkr.co/edit/gr3ha1lxgcFp3z4L148S?p=$p$ PVIEW ):

I am trying to write my first directive and am a bit confused. I would like to return a compiled template where the ng-click is functional. I have (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,为什么没有被输出的我的客户的指令?

In my plnkr, why is the my-customer directive not being outputted?

但我有点无能,下一步是什么。我有点弄链接和编译的概念,但我不知道如何来实现。我怎么能这样做呢?该文档是像糖蜜和我觉得我在做什么是难以置信的简单。

But am a bit clueless as to what the next step is. I kinda get the concept of linking and compiling but am not sure how to implement. How could I do this? The docs are like molasses and I feel what I'm doing is incredibly simple.

THX任何帮助。

推荐答案

您遇到的问题,这是不是在你的code以上明确的是,你覆盖已定义的点击功能的控制器。

The problem you are having, which is not clear in your code above is that you're overwriting the controller that has the click function defined.

您在code有这样两次: arcModule.controller('MainCtrl',函数($范围内){

You have this twice in your code: arcModule.controller('MainCtrl', function($scope) {

我所做的一切,让您的指令工作是删除第二个控制器定义,以便使用第一个具有点击功能(你真的只是需要将它们结合起来)。然后加入&LT; D​​IV我的客户的&GT;&LT; / DIV&GT; 到DOM。该指令踢和增加指令标记和点击功能工作正常。

All I did to make your directive work was remove the second controller definition so that the first one with the click function is used (you really just need to combine them). Then added <div my-customer></div> to the DOM. The directive kicked in and added the directive markup and the click function worked properly.

下面是完整的code更正:现场演示(点击)

Here's your full code corrected: 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>

这篇关于第一次写一个角指令和返回编译模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆