2014-07-10 10 views
3

저는 정말 간단한 각형 응용 프로그램을 가지고 있습니다. ng-click의 값에 1을 더하면됩니다.x = x + 1! = x ++?

<div ng-app="app" ng-controller="ctrl"> 
    <div ng-click="hello=hello+1">THIS WORKS ON CLICK: {{hello}}</div> 
    <div ng-click="hello++">THIS DOESN'T: {{hello}}</div> 
</div> 

JSFiddle 내가 할 수있을 것으로 예상보기 '++'를 사용하여 변수의 값 NG를 클릭,하지만 분명히 없습니다. 내가 뭔가 잘못하고 있니?

+0

둘 다 하나를 추가하면 어떤 점이 문제가됩니까? – Bit

+0

하나만 작동합니다. ++ 연산자가 클릭시 작동하지 않습니다. –

+1

@Bit hello ++는 그의 바이올린에 1을 더하지 않습니다. –

답변

9

ng-click 속성에는 각도 표현식이 필요합니다. 이 표현식은 자바 스크립트와 비슷하지만 자바 스크립트가 아니기 때문에 자바 스크립트에서 할 수있는 모든 것을 할 수는 없습니다. 자세한 내용은 https://docs.angularjs.org/guide/expression

살펴 링크에서 중요한 부분은 다음과 같습니다

이 코드에 대한

Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.

Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.

Instead use services like $window and $location in functions called from expressions. Such services provide mockable access to globals.

0

하나의 대안은 다음과 같습니다

<script> 
    var app = angular.module('app', []); 
    app.controller('ctrl', ['$scope', 

    function($scope) { 
     $scope.hello = 0; 
    $scope.sum = function(){ 
     $scope.hello++; 
    } 
    }]); 
</script> 
<div ng-app="app" ng-controller="ctrl"> 
    <div ng-click="hello=hello+1">CLICKING HERE UPDATES VALUE: {{hello}}</div> 
    <div ng-click="sum()">CLICKING HERE DOES NOT: {{hello}}</div> 
</div> 

그리고 합계() 함수가 될 수 있습니다 Angular의 $ parse 서비스로 구문 분석되지만, 그렇습니다. 합을 만들기 위해 더 많은 코드를 작성해야합니다.