为什么这样$在指令适用抛出值未定义错误 [英] Why this $apply in directive is throwing value undefined error

查看:140
本文介绍了为什么这样$在指令适用抛出值未定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写的采用了棱角分明的JS指令,在点击一个按钮都有递增计数值。

I'm trying write a directive using angular js, in which a button click has to increment a count value.

在单击事件处理程序我试图增加使用的范围值$适用结构,但它抛出一个语法错误:令牌未定义不是一个主要的前$ p $的前pression列NaN的pssion [统计++]开始在控制台[统计++] 错误。

On the click event handler I'm trying to increment the value using the scope.$apply construct but it is throwing an Syntax Error: Token 'undefined' not a primary expression at column NaN of the expression [count++] starting at [count++] error in the console.

标记

<div ng-app="myApp">
    <div ng-controller="MainCtrl">
        <div my-directive >
        </div>
    </div>
</div>

JS

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

myApp.directive('myDirective', function(){
    return {
        scope: {},
        template: '<div>{{count}}</div><input type="button" class="increment" value="Increment" />',
        link: function(scope, iElement, iAttrs, controller) {
            console.log('link', scope.count)
            iElement.on('click', '.increment', function(){
                console.log('click', scope.count);
                scope.$apply('count++');
            })
        },
        controller: function($scope){
            console.log('controller')
            $scope.count = 0;
        }
    };
});

myApp.controller('MainCtrl', ['$scope', function($scope){
}]);

演示:小提琴

推荐答案

更改你的前pression到

Changing your expression to

count = count + 1

解决问题。演示:小提琴

由于角不使用评估评估前pressions,您不能使用相当齐全的JavaScript在他们;这是其中一个例外。如果你的的需要一些更强大,你可以传递一个JavaScript函数 $适用(演示:的小提琴):

Since Angular doesn't use eval to evaluate expressions, you cannot use quite the full range of JavaScript in them; this is one of those exceptions. If you do need something a bit more powerful, you can pass a JavaScript function to $apply (demo: Fiddle):

scope.$apply(function() {
  scope.count++;
});

这篇关于为什么这样$在指令适用抛出值未定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆