angularjs转换不在我的自定义指令中工作

时间:2014-05-11 16:10:50

标签: angularjs

任何人都可以查看我的简单指令并弄清楚为什么转换不起作用?

HTML:          

<div ng-app="app">
<div ng-controller="MainController">
    <p>Your name</p><input ng-model="name"></input><button ng-click="greeting()">click</button>
    <greeter nationality="English" name="{{name}}">Hahahahah</greeter>
    <greeter nationality="French" name="{{name}}">Hahahahah</greeter>
    <greeter nationality="Russian" name="{{name}}">Hahahahah</greeter>
</div>    
</div>

JS:

var app = angular.module("app", []);



app.controller("MainController", function($scope) {

});

app.directive("greeter", function() {
  return {
    restrict: "AE",
    scope: {
      name: "@",
      nationality: "@"
    },
    transclude: true,
    template: "<div style='display:block'>{{name}}<div ng-transclude></div></div>",
    link: function(scope, elem, attr, ctrl) {
      scope.$watch("name", function() {
        elem.html(greeting + " " + scope.name);
      });
      var greeting = "";
      if (scope.nationality === "English") {
        greeting = "Hello";
      }
      else if (scope.nationality === "French") {
        greeting = "Bonjour";
      }
      else {
        greeting = "Howdy";
      }
    }
  };
});

1 个答案:

答案 0 :(得分:1)

使用elem.html(...)插入问候语时,您将覆盖已转录的内容。

您可以直接在模板中包含问候语文本,而不是使用jqLit​​e操作DOM。为此,greeting必须是范围属性(scope.greeting而不是var greeting)。

template: "<div style='display:block'>{{greeting}} {{name}}<div ng-transclude></div></div>",
link: function(scope, elem, attr) {
  if (scope.nationality === "English") {
    scope.greeting = "Hello";
  } else if (scope.nationality === "French") {
    scope.greeting = "Bonjour";
  } else {
    scope.greeting = "Howdy";
  }
}

如果您想亲自试用代码here it is on Plunkr