2015-10-26 33 views
0

我對AngularJS是全新的,並一直堅持這一點。我希望能夠有條件地在頁面上顯示一個Javascript警報箱。 假設我想要做這樣的事情:AngularJS插入警報框

<!DOCTYPE html> 
<html> 

    <head> 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
    </head> 

    <body> 
    <div ng-app="myApp" ng-controller="personCtrl"> 
     <script>{{warning}}</script> 
    </div> 

    <script> 
    var app = angular.module('myApp', []); 
    app.controller('personCtrl', function($scope) { 
     $scope.warning = "alert('This is a warning');"; 
    }); 
    </script> 

    </body> 

</html> 

所以我認爲這是與AngularJS消毒串並取出的javascript來做。一些谷歌搜索後,我嘗試了以下內容:

$scope.warning = $sce.trustAsJS("alert('This is a warning');"); 

我也試過trustAsHtml和字符串中添加的腳本標記,但也顯示alertbox。有人能告訴我並告訴我發生了什麼問題嗎?

+1

您應該將'alert(..)'行作爲正常代碼 – svarog

+0

放置在您的控制器中,您不需要使用示波器,只需將警報放在要顯示的位置,就像您在JavaScript中使用的方式一樣。 – Shuvro

回答

0

它實際上應該是這樣的:

var myApp = angular.module('myApp',[]); 

function MyCtrl($scope) { 
    $scope.name = 'Superhero'; 

    if ($scope.name==='Superhero') { 
     alert("hello"); 
    } 
} 

,如果你想可以通過在視圖改變模型有條件地顯示嘗試這樣的警告:每次

var myApp = angular.module('myApp',[]); 

function MyCtrl($scope) { 
    $scope.name = 'Superhero'; 

    $scope.$watch('name', function(newVal, oldVal) { 
     alert("hello"); 
    }) 
} 

現在你會在您的視圖中更改'名稱'模型,將彈出提醒

有關手錶的更多信息,請參閱doc

0

您希望$ scope.warning是一個函數,而不是執行一個或一個字符串的結果。

$scope.warning = function() { alert('This is a warning'); }; 

這樣可以在以後的視圖中調用:warning()應顯示警報。

另外,由於警報是一個函數,你可能只是想用它作爲$ scope.warning:

$scope.warning = alert; 

+

warning('this is a warning') 

會產生相同的結果。