如何在javascript数据字段中绑定AngularJs变量



我想在javascript数据字段中绑定一个从json文件中获取的变量,但我不能使用{{}}运算符,因为它是在之后处理的。

<div class="milestone">
  <div class="number" data-animation="true" data-animation-type="number" data-final-number="{{itemSold}}"></div>
  <div class="title">Items Sold</div>
</div>

通过这种方式,它给了我一个 NaN,因为他看不到商品已售出的价值。

这就是项目销售的回收方式

var app = angular.module('app', []);
app.controller('AppCtrl', ['$scope', '$http', function($scope, $http) 
{
  $http.get('app/shared/homeStatistics.json').success(function(data){
   $scope.itemSold = data.itemSold;
   $scope.themeAndTemplate = data.themeAndTemplate;
   $scope.members = data.members;
  });
}]);

我认为我必须使用以前处理过的像ng-bing这样的东西,但我不知道怎么做。

感谢您的所有建议,对不起我的英语不好

编辑 1

数据

被正确检索,但在数据最终编号之后处理,因此他在开头读了一个"

我的 JSON 数据

{
"itemSold":1000
}

编辑 2

这里是如何处理数据的最终数字

var handlePageScrollContentAnimation = function() {
$('[data-scrollview="true"]').each(function() {
    var myElement = $(this);
    var elementWatcher = scrollMonitor.create( myElement, 60 );
    elementWatcher.enterViewport(function() {
        $(myElement).find('[data-animation=true]').each(function() {
            var targetAnimation = $(this).attr('data-animation-type');
            var targetElement = $(this);
            if (!$(targetElement).hasClass('contentAnimated')) {
                if (targetAnimation == 'number') {
                    var finalNumber = parseInt($(targetElement).attr('data-final-number'));
                    $({animateNumber: 0}).animate({animateNumber: finalNumber}, {
                        duration: 1000,
                        easing:'swing',
                        step: function() {
                            var displayNumber = handleAddCommasToNumber(Math.ceil(this.animateNumber));
                            $(targetElement).text(displayNumber).addClass('contentAnimated');
                        }
                    });
                } else {
                    $(this).addClass(targetAnimation + ' contentAnimated');
                }
            }
        });
    });
});
};

我建议将attr.$observer与finalNumber指令一起使用。这将触发一个函数,只要有更新就会执行。话虽如此,它不仅呈现一次,每当值更改时,视图都会更新。

.directive('finalNumber',function() {
  function link(scope, element, attrs) {
    $attrs.$observe('finalNumber', function(value) {
       if (!isNaN(value)){
          //update accordingly, it's kind of hack to
          //bring this code to angular. It's better to write all these
          // as angular directives.
          handlePageScrollContentAnimation(); 
       }
    });
  }
  return {
    link: link
  };
});

从jQuery背景移动到角度时,你需要改变你的心态。Angular是一个MVC框架,主要基于数据绑定。使用数据绑定时,视图不应关心何时以及如何更新模型,但每当有更新时,视图都应知道它并相应地更新视图

上面的例子应该是使用角度的正确方法。但正如我所说,将你的jQuery代码带到angular是一个相当不错的黑客,所有这些都应该写成指令。我不确定您是否需要在第一次更新后仅运行一次 jQuery 代码(多次运行可能会导致副作用)。您可能需要一些技巧。不建议这样做,如果可能的话,你应该把所有这些写成指令(scrollviewanimationfinalNumber ,..)

.directive('finalNumber',function() {
      function link(scope, element, attrs) {
        var hasRun = false;//hack the code to run only once.
        $attrs.$observe('finalNumber', function(value) {
           if (!isNaN(value) && !hasRun){
              //update accordingly, it's kind of hack to
              //bring this code to angular. It's better to write all these
              // as angular directives.
              handlePageScrollContentAnimation(); 
           }
        });
      }
      return {
        link: link
      };
    });

如果我理解正确,您希望在加载组件/指令/控制器后立即拥有数据。

在这种情况下 - 在控制器中使用 solve,它会将 ajax 请求的结果注入控制器,到加载控制器时,您将拥有所有数据。

路由器

app.config(function ($routeProvider) {
  $routeProvider
    .when('/',
    {
      templateUrl: "app.html",
      controller: "AppCtrl"
      resolve: {
        statResponse: function () {
          return $http.get('app/shared/homeStatistics.json');
        }
      }
    }
  )
});

控制器

app.controller('AppCtrl', ['$scope', 'statResponse', function($scope, statResponse) 
{
  if(statResponse && statResponse.status === 200) {
   $scope.itemSold = statResponse.data.itemSold;
   $scope.themeAndTemplate = statResponse.data.themeAndTemplate;
   $scope.members = statResponse.data.members;
  }
}]);

另一种方法是在元素上使用 ng-cloak。它将隐藏元素,直到解析所有变量。

<div class="number" ng-cloak data-animation="true" data-animation-type="number" data-final-number="{{itemSold}}"></div>

希望有帮助。

在大多数情况下没关系。如果您不想要任何NaN,您有几种选择:

  • 初始化范围变量,例如,"挂起..."
  • ng-ifng-show包裹
  • 更复杂的解决方案(例如静止角度)

显然,您正在尝试在解析之前处理 data-final-number="{{itemSold}}" 属性。要在此之后处理它,请确保仅在您检索 JSON 数据并且 AngularJS 生命周期已经为您解决了它之后才调用处理程序。为此,您可以使用 AngularJS 的 $timeout ,因此它将在 AngularJS 操作排队并执行。

var app = angular.module('app', []);
app.controller('AppCtrl', ['$scope', '$http', function($scope, $http, $timeout) 
{
  $http.get('app/shared/homeStatistics.json').success(function(data){
   $scope.itemSold = data.itemSold;
   $scope.themeAndTemplate = data.themeAndTemplate;
   $scope.members = data.members;
   //calling handler after AngularJS applied all two-way-bindings
   $timeout(function() {
     handlePageScrollContentAnimation();
   }, 0);
  });
}]);

有关更多信息,请阅读:无论如何,当 Angular 完成向 DOM 添加范围更新时触发方法?

我想

在"itemSold"变量上放置监视,每当从$http调用中获取值时,我都会调用handlePageScrollContentAnimation处理程序。

var watchItemSold = $scope.$watch('itemSold', function(newVal, oldVal, scope){
   if(newVal != oldVal){
      handlePageScrollContentAnimation(); //call handler
      watchItemSold(); //watch destructor will ensure that handler will call once
   }   
});

希望这对您有所帮助。嗡嗡。

最新更新