2015-07-21 51 views
8

我是新來的angular並在控制檯TypeError: name.replace is not a function中不斷收到以下錯誤。我不確定究竟是什麼造成的,但它似乎是由ng-style聲明造成的,也許與駝峯事件有關?Angular TypeError:name.replace不是ng風格的函數

我不明白的部分是爲什麼ng-style="isFrontView() || !matches && {'display': 'none'}"會拋出錯誤,但ng-style="!isFrontView() || !matches && {'display': 'none'}"不會拋出錯誤。

爲了解決這個問題,我嘗試從函數名中刪除camelCase並全部小寫。我也試圖使用!!isFrontView(),但似乎都沒有刪除錯誤信息。

是否有人知道這個錯誤消息的原因是什麼以及可能的修復?

Error Message

HTML模板:

<div class="system-view"> 
    <div class="controller-container fill" id="systemView1" ng-style="isFrontView() || !matches && {'display': 'none'}"> 
     <canvas id="canvasLayer-shell" data-layername="front" width="617" height="427"></canvas> 
     <i ng-if="!matches" class="fa fa-repeat toggle-view" ng-click="changeView()" ng-touch="changeView()"></i> 
    </div> 
    <div class="controller-container fill" id="systemView2" ng-style="!isFrontView() || !matches && {'display': 'none'}"> 
     <canvas id="canvasLayer-shell" data-layername="back" width="617" height="427"></canvas> 
     <i ng-if="!matches" class="fa fa-undo toggle-view" ng-click="changeView()" ng-touch="changeView()"></i> 
    </div> 
</div> 

後端代碼:

$scope.frontView = true; 
$scope.matches = true; 

$scope.isFrontView = function() { 
    return $scope.frontView; 
}; 

$scope.changeView = function() { 
    $scope.frontView = !$scope.frontView; 
}; 

附:即使在控制檯出錯的情況下,一切仍然正常。

+0

旁註:你爲什麼不只是使用NG式表達的NG-顯示/ NG隱藏nstead隱藏元件。 – PSL

+0

@PSL當前應用程序設置爲同時繪製兩個畫布,所以它們必須留在DOM中。 – Steven10172

+0

如果使用ng-show/ng-hide。他們會留在DOM中,而不像ng-if。 – PSL

回答

13

您的潛在問題是由於ng-style的使用不正確造成的。 ng-style sets a watcher on the expression並設置爲element's style with the help of jquery/jqlite element.css。並將element.css裏面的css屬性(name)轉換爲標準駱駝套管(which uses regex string replace)。在特定情況下,表情評估爲布爾值(true)而不是一個對象(ng-style does this for each property)和布爾沒有replace屬性(其可一個對象上),並且因此它失敗。您可以通過使用字符串連接將表達式轉換爲字符串來測試。

ng-style="'' + (isFrontView() || !matches && {'display': 'none'})"

縱觀表達所有你需要它來隱藏和顯示元素,你很可能利用ng-show/ng-hide指令來實現這一目標。

0

這是一個遲到的答案,但我可能會幫助像我這樣的問題的其他人。在我的情況下,錯誤是a.replace不是函數,最後我找到了原因。這是由於ng風格發生的,並且表達式是data-ng-style="isCompare==true ? {'max-height':'423'} : ***' '*** ....單個線索之間的空間導致了錯誤。移除空間後,錯誤消失。

0

如果評估的表達式返回錯誤的類型,就會發生這種情況。

表達式計算:

ng-style="$vm.getStyles()" 

必須返回一個對象常量:

return { order: -1 };