一尘不染

如何使AngularJS编译指令生成的代码?

angularjs

请帮助我,如何使AngularJS编译指令生成的代码?

您甚至可以在这里找到相同的代码,http://jsbin.com/obuqip/4/edit

的HTML

<div ng-controller="myController">
    {{names[0]}} {{names[1]}}
    <br/> <hello-world my-username="names[0]"></hello-world>
    <br/> <hello-world my-username="names[1]"></hello-world>
    <br/><button ng-click="clicked()">Click Me</button>
</div>

Java脚本

var components= angular.module('components', []);
components.controller("myController",
    function ($scope) {
        var counter = 1;
        $scope.names = ["Number0","lorem","Epsum"];
        $scope.clicked = function() {
            $scope.names[0] = "Number" + counter++;
        };
    }
);

// **Here is the directive code**
components.directive('helloWorld', function() {
    var directiveObj =  {
        link:function(scope, element, attrs) {
            var strTemplate, strUserT = attrs.myUsername || "";
            console.log(strUserT);
            if(strUserT) {
                strTemplate = "<DIV> Hello" + "{{" + strUserT +"}} </DIV>" ;
            } else {
                strTemplate = "<DIV>Sorry, No user to greet!</DIV>" ;
            }
            element.replaceWith(strTemplate);
        },
        restrict: 'E'
    };
    return directiveObj;
});

阅读 245

收藏
2020-07-04

共1个答案

一尘不染

这是一个既不使用编译功能也不使用链接功能的版本:

myApp.directive('helloWorld', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      myUsername: '@'
    },
    template: '<span><div ng-show="myUsername">Hello {{myUsername}}</div>'
    + '<div ng-hide="myUsername">Sorry, No user to greet!</div></span>',
  };
});

请注意,模板被包装在中,因为模板需要具有一个根元素。(如果没有,它将有两个

根元素。)

需要对HTML进行少许修改以进行插值:

<hello-world my-username="{{names[0]}}"></hello-world>

小提琴

2020-07-04