是否可以使用隔离范围呈现角度指令模板?

时间:2017-05-17 10:31:30

标签: javascript angularjs angularjs-directive angularjs-ng-transclude

我遇到了一个使用孤立范围的角度指令的奇怪行为。显然,使用旧范围解析模板(即使是已转换),而不是新范围。

这听起来有点奇怪,因为它违反了“隔离”。指令的范围

html:

<div ng-app="myApp">
  <div ng-controller="MyController">
    out prop = {{prop}}
    <div my-directive prop="'valueIN'">
      in prop = {{prop}}
    </div>
  </div>
</div>

js

function MyController($scope) {
  $scope.prop = 'valueOUT';
}

angular.module('myApp',[]).directive('myDirective', function() {
  return {
    scope: { prop: '=' }
  };
});

输出:

Angular 1.1

out prop = valueOUT
in prop = valueIN

Angular 1.2

out prop = valueOUT
in prop = valueOUT
对我来说这听起来很奇怪...... 转换模板也有同样的行为。

是否有可能在1.2中获得1.1行为?

相应的小提琴: https://jsfiddle.net/4s1fxjmq/

1 个答案:

答案 0 :(得分:1)

一种方法是在适当的范围内重新编译元素:

.directive('myDirective', ['$compile', function($compile) {
  return {
    scope: {
      prop: '='
    },
    link: function(scope, element, attr) {
      attr.$set('myDirective', null)
      $compile(element)(scope)
    }
  }
}])