search

Home  >  Q&A  >  body text

angular.js - ng-repeat嵌套的directive link函数未执行

http://codepen.io/whb/pen/wzjWYv

初始化的时候,可以走到link函数中将原数据处理之后再做显示

当点击刷新之后

实在无法理解 当ng-repeat中数据刷新之后 嵌套的directive未执行link函数,跪求各位大神指导

代码如下:

(function() {
  'use strict';
  var app = angular.module('plunker', []);
  app.controller('MainCtrl', function($scope) {
    $scope.list = [{
      name: "张三",
      age: 23
    }, {
      name: "李四",
      age: 63
    }];
    //刷新按钮
    $scope.load = function() {
      $scope.list = [{
        name: "张三1",
        age: 23
      }, {
        name: "李四1",
        age: 63
      }];
    };
  });
  app.directive('item', function() {
    return {
      restrict: 'A',
      template: "<p>姓名:</p>  <p>{{ item.name }}</p>  <p>昵称:</p>  <p>{{ item.nickName }}</p>  <p>年龄:</p>  <p>{{item.age}}</p>",
      scope: {
        item: "=",
      },
      link: function(scope, element, attrs) {
        scope.item.nickName = scope.item.name + "nick";
        console.log(scope.item);
      }
    }
  });
})();
<p ng-app="plunker">
  <p ng-controller="MainCtrl"  style="text-align: center;">
    <p >
      <p ng-repeat="item in list track by $index" class="items-warp">
        <p item="item" class="row"></p>
      </p>
    </p>
    <button ng-click="load()">刷新 </button>
  </p>
</p>
怪我咯怪我咯2744 days ago558

reply all(1)I'll reply

  • 为情所困

    为情所困2017-05-15 17:09:38

    I will tell you my opinion, but it may not be correct.

    The reason should be caused by your track by syntax on ng-repeat.

    The official documentation says that ngRepeat detects whether the corresponding viewModel has changed based on $watchCollection. Adding track by is equivalent to attaching new conditions to this detection mechanism. When you click refresh for the second time, ngRepeat detects whether the corresponding viewModel has changed based on track by. The judgment obtained from the conditions actually does not require re-rendering the Dom, so the instructions you define will not be compiled again. The link method is only called after compile, so the link method cannot be called.

    Analysis of compile and link: Portal

    reply
    0
  • Cancelreply