ng-click

时间:2016-11-30 06:05:12

标签: javascript angularjs angularjs-directive angular-directive

单击按钮后,以下代码无效。似乎指令不再编译。任何人都可以帮我解决这个问题!

HTML:

  <button ng-click="run()">click</button>
  <p>Hello {{name}}!</p>
  <customdir filterby="name"></customdir>

可在此处找到类似的代码http://plnkr.co/edit/OQqLeUIoFNhkqSoeIdyM?p=preview

Javascript:

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

app.controller('MainCtrl', function($scope) {

$scope.name = 'World';

$scope.run = function() {
$scope.name = 'goal';
};

});
app.directive('customdir', function($compile) {
var getTemplate = function(filterby) {
switch (filterby) {
  case 'World':
    return '<div class="col-lg-1" id="ready">' +
      '<img ng-src="http://plnkr.co/img/plunker.png" style="height: 35px; width: 35px; margin-left: 70px; margin-bottom: 3px" />' +
      '</div>';
  case 'goal':
    return '<b>tttttt !!</b>';
  default:
    return '<b>Error !!</b>';
 }
}
return {
restrict: 'E',
scope: {
  filterby: '='
},
 link: function(scope, element, attrs) {
   var el = $compile(getTemplate(scope.filterby))(scope);
   element.replaceWith(el);
  }
 };
});

2 个答案:

答案 0 :(得分:1)

更改编译时的顺序vs将其放在dom中,详细了解here

var el =angular.element('your html');
element.replaceWith(el);
$compile(el)(scope);

答案 1 :(得分:1)

您必须使用scope.$watch('filterby', function(newValue, oldValue) { })来处理模型更改。

工作副本:

&#13;
&#13;
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

$scope.run = function() {
$scope.name = 'goal';
};

});


app.directive('customdir', function($compile) {
var getTemplate = function(filterby) {
switch (filterby) {
  case 'World':
    return '<div class="col-lg-1" id="ready">' +
      '<img ng-src="http://plnkr.co/img/plunker.png" style="height: 35px; width: 35px; margin-left: 70px; margin-bottom: 3px" />' +
      '</div>';
  case 'goal':
    return '<b>tttttt !!</b>';
  default:
    return '<b>Error !!</b>';
 }
}
return {
restrict: 'E',
scope: {
  filterby: '='
},
 link: function(scope, element, attrs) {
     
   scope.$watch('filterby', function(newValue, oldValue) {
     var el = $compile(getTemplate(scope.filterby))(scope);
     element.replaceWith(el);
     element = el;
   });
  }
 };
});
&#13;
<!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.2.x" src="http://code.angularjs.org/1.2.5/angular.js" data-semver="1.2.5"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <customdir filterby="name"></customdir>
    <button ng-click="run()">click</button>
  </body>

</html>
&#13;
&#13;
&#13;