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

2023-11-23

请帮助我,我们如何让 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>

JavaScript

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;
});

这是一个不使用编译函数和链接函数的版本:

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>

Fiddle.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让AngularJS编译指令生成的代码? 的相关文章