小编Tim*_*Mac的帖子

当我调用element.remove时为什么不触发$ destroy?

我无法弄清楚为什么在以下示例中未触发$ destroy事件.有人可以解释为什么它没有被触发,在什么情况下它会被触发?

以下是plunkr:http://plnkr.co/edit/3Fz50aNeuculWKJ22iAX?p=preview

JS

angular.module('testMod', [])
.controller('testCtrl', function($scope){
  $scope.removeElem = function(id) {
    var elem = document.getElementById(id);
    angular.element(elem).remove();
  }
}).directive('testDir',[function() {
  return {
    scope:true,
    link: function(scope) {
      console.log('in directive');
      scope.$on('$destroy', function(){
        alert('destroyed');
      })
    }
  }
}]);
Run Code Online (Sandbox Code Playgroud)

HTML

<body ng-controller='testCtrl'>
  <div testDir id='test'>I will be removed.</div>
  <button ng-click='removeElem('test')'>remove</button>
</body>
Run Code Online (Sandbox Code Playgroud)

angularjs angularjs-directive angularjs-scope

24
推荐指数
1
解决办法
2万
查看次数

angularjs:ngModel controller $ parser&$ formatter在删除元素后仍然触发

在下面的例子中,我不明白为什么在删除元素后,angular仍然会解析解析器和格式化程序.我应该在指令中手动清理ngModel控制器吗?如果是这样,我该怎么做?

要查看我在说什么,请查看plunker,和

  1. 打开一个控制台
  2. 点击"删除"按钮
  3. 单击"更改模型"按钮
  4. 注意格式化程序仍在触发

plunker:http://plnkr.co/edit/R7v5nB8JaQ91WcDGU8BC?p = preview

JS

angular.module('testMod', [])
.controller('testCtrl', function($scope){
  $scope.test = "test";
  $scope.removeElem = function(id) {
    var elem = document.getElementById(id);
    angular.element(elem).remove();
  }
}).directive('testDir',[function() {
  return {
    require: 'ngModel',
    scope:true,
    link: function(scope, elem, attr, ctrl) {
      console.log('in directive');
      ctrl.$parsers.unshift(function (newValue) {
          console.log('directive parser');
          return newValue;
      });
      ctrl.$formatters.unshift(function (newValue) {
          console.log('directive formatter');
          return newValue;
      });
    }
  }
}]);
Run Code Online (Sandbox Code Playgroud)

HTML

<body ng-controller='testCtrl'>
    <input id='test' test-dir ng-model='test'/>
    <button ng-click="removeElem('test')">remove</button>
    <button ng-click="test = test + 'a'">change model</button>
    <div>{{test}}</div> …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs angularjs-directive

7
推荐指数
1
解决办法
2332
查看次数