0

下面的方法有效......但是,它仅在将 $timeout 添加到 tabList() 函数时才有效。ng-init 在 DOM 渲染之前执行,因此 document.getElementById('')'s 以未定义的形式返回。在附加元素之前,我必须强制延迟 1 到 2 秒,直到 DOM 加载。这不是最佳的,但它确实有效。我正在寻找另一种更清洁且不依赖于延迟执行的方法。

angular.module('starter.controllers', [])

.constant('constants', {
   tabColors: {
     curID:0,
   },
})

.controller('TabsCtrl', function($scope,Tabs,constants) {  
  $scope.constants = constants; 
  $scope.tabList = function() {
        var tID = $scope.constants.tabColors ;
    console.log(tID.curID) ;
    if (tID.curID) {
        $timeout(function() {
        document.getElementById('bike_tabItem_'+tID.curID).style.color = 'green' ;
        document.getElementById('bike_tabItem_'+tID.curID).style.color = 'black' ;
      },1000) ;
    }
  }
})

.controller('TabDetailCtrl', function($state,$scope,$stateParams,Tabs,constants) {
  $scope.constants = constants; //make it available constants on html
  $scope.itemSelect = function(thisID) {
    $scope.constants.tabColors.oldID = $scope.constants.tabColors.curID ;
    delete $scope.constants.tabColors['tabID_'+$scope.constants.tabColors.curID] ;
    $scope.constants.tabColors.curID = thisID ;
    $scope.constants.tabColors['tabID_'+thisID] = 'green' ;
  }
})

// 在 Tab.html 上的 HTML 中:

<ion-item cache-view="false" id="tab_tabItem_{{tab.tabID}}" ng-init="tabList()">

// 在 HTML 中的 Tab-Detail.html

<button id="tab_button" class="button button-small button-outline button-positive" ng-click="itemSelect({{tab.tabID}});">
Select this item
</button>

另外,调用 tabList() 的另一种方法是: ng-init="tabList('{{tab.tabID}}')"

这为您提供了一种通过 ng-init 传递值的方法,与我上面的调用不同,它为您提供更好的控制,而无需定义全局变量。尽管您仍然需要一个全局变量来跟踪哪个元素变为绿色,因此您可以在将新元素设置为绿色之前将其设置回黑色。

4

1 回答 1

0

正如 AngularJS 文档中所说,您应该避免使用ng-init

ngInit 唯一合适的用途是为 ngRepeat 的特殊属性设置别名,如下面的演示所示。除了这种情况,您应该使用控制器而不是 ngInit 来初始化作用域上的值。

要在控制器之间传递变量,您可以使用provider

于 2015-06-11T11:42:46.493 回答