Angular指令模板上的增量值

时间:2017-04-06 12:02:32

标签: javascript angularjs scope

这是我的问题,我想将带有模板的指令应用于页面上的元素,并带有增量值。

我的问题是我的值保持在0,我在stackoverflow上尝试了很多答案,但没有成功使用它们,我对角度很新。

这是我的指示:

namespace DataLayer.Entities
{
    [Table("Games")]
    public class Game : IEntity
    {   
        public Guid Id { get; set; }
        public int PlayerOneId { get; set; }
        public int PlayerTwoId { get; set; }
        public Guid RoundId { get; set; }
        [ForeignKey("RoundId")]
        public Round Parent { get; set; }
    }
}

namespace DataLayer.Entities
    {
      [Table("Rounds")]
      public class Round
      {     
         public ICollection<Game> Games { get; set; }          
         public Guid Id { get; set; }
         public bool HasStarted { get; set; }
         public DateTime TimeStarted { get; set; }
         public int RoundNumber { get; set; }
       }
    }

根据要求,这是我的哈巴狗模板:

app.directive('loader', function ($window) {

return {
    restrict: 'E',
    replace: true,
    transclude: true,
    controller: function($scope){
        if (!$scope.counter)
            $scope.counter = 0;
        else
            $scope.counter++;
    },
    template: '<div ng-class=\"({ \'display-opacity\' : ready{{counter}} })\" ng-transclude></div>',
};

});

1 个答案:

答案 0 :(得分:1)

在阅读了关于transclude选项的文档之后,我打算写一些东西(见下文),但是在使用codepen之后,我变得更加困惑。我想,你要做的事情是相当困难的。

快速(也许是肮脏的)解决方案是为您的柜台使用服务。 https://codepen.io/anon/pen/vxwpxo

app.directive('loader', function(myCounter) {
  return {
    restrict: 'E',
    replace: true,
    scope: {},
    template: '<div>{{opacity}}</div>',
    link: function(scope) {
      scope.opacity = myCounter.get();
    }
  };
});

app.factory('myCounter', function() {
  var counter = 0;

  return {
    get: function() {
      return counter++;
    }
  };
});

以前的想法:

  

transclude选项会更改范围嵌套的方式。它使得transcluded指令的内容具有指令之外的任何范围,而不是内部的任何范围。这样做,它使内容访问外部范围。

     

请注意,如果指令没有创建自己的范围,那么scope中的scope.name = 'Jeff';将引用外部范围,我们会在输出中看到Jeff

     

https://code.angularjs.org/1.4.6/docs/guide/directive

我不知道,如果你的指令中有一个控制器,那里定义了counter。如果是,指令控制器中的代码不会更改counter的值(如果我已正确理解文档)。如果不是,则每个指令将实例化其自己的counter,并且因为它尚未设置if (!$scope.counter)将始终为真。如果指令具有孤立的范围,它的行为会有所不同。 我感到困惑!