2016-12-29 33 views
2

我的代碼運行良好,直到我在兩個單詞之間使用空格爲止。 我正在使用AngularJs。

stringAmi = '<i class="fa fa-user-plus fa-2x" ng-click="demandeAmiNotif(' + $scope.invite + ');"></i>'; 

$ scope.invite是我喜歡保持用戶的名稱字符串:「雨果」 我有這樣的錯誤:

Error: [$parse:syntax] Syntax Error: Token 'Hugo' is unexpected, expecting [)] at column 22 of the expression [demandeAmi(Victor Hugo);] starting at [Hugo);]. 
+0

你仍然需要產生有效的JS。 –

+0

因此,所執行的代碼行是'demandeAmiNotif(Victor Hugo);'是的,這是一個語法錯誤。 – David

+0

但它與demandeAmiNotif(Victor)合作;我的意思是當$ scope.invite =「Victor」; – DionysoSong

回答

2

我認爲你有太多的嵌套的字符串模板和事情變得越來越複雜。但是,在這種情況下,缺少轉義函數調用參數,因爲它位於字符串內部,並且不作爲參數傳遞,而是作爲字符串傳遞。

var stringAmi = 
    '<i class="fa fa-user-plus fa-2x" ng-click="demandeAmiNotif(' 
    + '\'' + $scope.invite + '\'' 
    + ');"></i>'; 

但嚴重的是,雖然,它看起來可怕,但,我不知道爲什麼你必須做這樣的方式,但可以考慮使用不同的方法,實實在在地更容易維護。

angular.module('myApp', []) 
 
    .controller('myController', function($scope) { 
 
     $scope.invite = 'Vitor Hugo'; 
 
     $scope.demandeAmiNotif = function(name) { 
 
      console.log(name); 
 
     }; 
 
     $scope.stringAmi = 
 
      '<button ng-click="demandeAmiNotif(' + '\'' + $scope.invite + '\'' + ');">Click this!</button>'; 
 
    }) 
 
    .directive('bindHtmlCompile', function($compile) { 
 
     return { 
 
      restrict: 'A', 
 
      link: function(scope, element, attrs) { 
 
       scope.$watch(function() { 
 
        return scope.$eval(attrs.bindHtmlCompile); 
 
       }, function(value) { 
 
\t \t \t \t 
 
        element.html(value && value.toString()); 
 
\t \t \t \t \t 
 
        var compileScope = scope; 
 
        if (attrs.bindHtmlScope) { 
 
         compileScope = scope.$eval(attrs.bindHtmlScope); 
 
        } 
 
        $compile(element.contents())(compileScope); 
 
       }); 
 
      } 
 
     }; 
 
    }); 
 

 
angular.element(function() { 
 
    angular.bootstrap(document, ['myApp']); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script> 
 
<div ng-controller="myController"> 
 
    <div bind-html-compile="stringAmi"></div> 
 
</div>

+0

好吧,我使用科爾多瓦,谷歌地圖和angularJs這就是爲什麼它看起來很可怕,我現在有一個其他錯誤:錯誤:[$ parse:ueoe]意外的表達式結束:demandeAmiNotif( – DionysoSong

+0

@DionysoSong好吧,如果你有機會,嘗試一個簡單的解決方案,關於新的錯誤,對此感到遺憾,實際上你必須避免使用撇號而不是引號,我已經更新了我的答案 –

+0

非常感謝你,工作得很好! – DionysoSong