为什么ng-click没有附加到dom?

时间:2016-12-16 14:31:56

标签: javascript angularjs

var erroMessage = "<br/>For<br/><a ng-click='RR.hiphen();'><strong>Visit</strong></a>");
$scope.Error = {
    alertType:"error",
    title: "",
    message: GlobalObjectErrorMessage + erroMessage,
};      

如果没有像下面的ng-click那样我会变得简单:

<a><strong>Visit</strong></a>

2 个答案:

答案 0 :(得分:0)

你必须使用$ compile编译它,因为它不是dom的一部分。

<dir content="{{ erroMessage }} ">

errorMessage变量应该是$ scope的一部分,因此它可以在html视图中访问,然后将指令添加到控制器或任何其他地方通过编译将内容转换为html。

.directive('dir', function ($compile, $parse) {
          return {
              restrict: 'E',
              link: function (scope, element, attr) {
                  scope.$watch(attr.content, function () {
                      element.html($parse(attr.content)(scope));
                      $compile(element.contents())(scope);
                  }, true);
              }
          }
      }) 

答案 1 :(得分:0)

由于我没有完整的js代码,我会安排我的数据并点击该函数调用发出警报

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    
    <div dynamic="erroMessage "></div>
  </body>
<script>
  var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  
  $scope.erroMessage  = "<br/>For<br/><a ng-click='hey();'><strong>Visit</strong></a>";
$scope.Error = {
    alertType:"error",
    title: "",
    message: "hey" + $scope.erroMessage ,
}; 

$scope.hey=function(){
  alert("i am coming from your vist click");
}
});
app.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(erroMessage ) {
        ele.html(erroMessage );
        $compile(ele.contents())(scope);
      });
    }
  };
});

</script>
</html>