【问题标题】:How to get updated value for isolated scope using angular directive?如何使用角度指令获取隔离范围的更新值?
【发布时间】:2016-12-09 19:32:04
【问题描述】:

我有一个指令可以让浏览器在第一次加载页面时获得string 值。但是当值动态变化时string 没有被更新xml 保持不变。知道在以下指令中实现了什么错误以获取 xml 的更新值吗?

html

<div class="tab-pane fade" id="tab2default"><pre class="prettyprint lang-xml" xml="{{string}}"></pre></div>

directive.js

angular.module('angularModelerApp').directive('prettyprint', function($document) {
  return {
    restrict: 'C',
    scope: {
      xml: '@'
    },
    link: function postLink(scope, element, attrs) {
      element.text(vkbeautify.xml(scope.xml, 4));
    }
  };
});

【问题讨论】:

    标签: javascript angularjs xml angularjs-directive


    【解决方案1】:

    链接函数仅在指令第一次插入 DOM 时执行一次。因此,Angular 仅在您的代码中获取 scope.xml 的初始值,并且不订阅更新。

    你可能想要这样的东西:

    angular.module('angularModelerApp').directive('prettyprint',       function($document) {
      return {
        restrict: 'C',
        scope: {
          xml: '@'
        },
        link: function postLink(scope, element, attrs) {
          scope.$watch('xml', function(newVal, oldVal) {
             element.text(vkbeautify.xml(newVal, 4));
          });
        }
      };
    });
    

    有关更多详细信息,请参阅文档中有关 $watch 的部分: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多