服务仅在 `$rootScope.$appy()` 应用后有效

service only works after `$rootScope.$appy()` applied

我正在从 angular-service 加载模板,但这不会更新 template,除非我使用 $rootScope.$appy()。但我的问题是,这样做是更新模板的正确方法吗?

这是我的代码:

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

app.service('modalService', function( $rootScope ) {


  this.hide = function () {

    this.show = false;


  }

  this.showIt = function () {

    this.show = true;

  }

  this.setCategory = function ( category ) {

     return this.showPath = category+'.html'

  }

  this.showCategory = function (category) {

    this.setCategory( category )
    $rootScope.$apply(); //is this correct?
  }

})

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

  $scope.view = "home view";

});

app.controller('home', function($scope, modalService) {

  $scope.name = 'World';
  $scope.service = modalService; 

});

//header directive

app.directive('headerDir', function( modalService) {

  return {
      restrict : "E",
      replace:true,
      templateUrl:'header.html',
      scope:{},
      link : function (scope, element, attrs) {


         element.on('click', '.edit', function () {
            modalService.showIt();
            modalService.showCategory('edit');
         });

         element.on('click', '.service', function () {
           modalService.showIt();
           modalService.showCategory('service');

         })

      }
  }

});

app.directive('popUpDir', function () {

  return {
    replace:true,
    restrict:"E",
    templateUrl : "popup.html"
  }

})

如果我在这里错了,请有人告诉我吗?或者任何人都可以告诉我正确的方法吗?

单击顶部的链接以加载合适的模板。然后点击背景屏幕关闭。

Live Demo

如果您不使用 Angular 的错误处理,并且您知道您的更改不应传播到任何其他范围(根、控制器或指令),并且您需要优化性能,您可以专门在控制器的 $scope 上调用 $digest。这样脏检查就不会传播。否则,如果您不希望错误被 Angular 捕获,但需要将脏检查传播到其他 controllers/directives/rootScope,您可以不使用 $apply 包装,而是调用 $rootScope。 $apply() 在你做出改变之后。

参考此 link 也 Angular - Websocket and $rootScope.apply()

使用ng-click处理点击事件。

模板:

<div ng-repeat="item in items">
  <div ng-click="showEdit(item)">Edit</div>
  <div ng-click="delete(item)">Edit</div>
</div>

控制器:

....
$scope.showEdit = function(item){
....
}
$scope.delete = function(item){
....
}

如果您使用 jquery 或任何其他外部库并修改 $scope,angular 无法知道是否发生了变化。相反,如果您使用 ng-click,您可以让 angular track/detect 在 ng-click 处理程序完成后更改。

这也是 angular 的做法。仅当没有其他方法可以拯救世界时才使用 jquery。