【问题标题】:Variable in $scope returns NaN when used in a directive?$scope 中的变量在指令中使用时返回 NaN?
【发布时间】:2014-08-24 20:01:54
【问题描述】:

我正在尝试这样做,以便我可以在我的 angularJS 应用程序中添加一个带有按钮的文本区域。可以有尽可能多的用户喜欢的文本区域,用于向向导系统添加内容。显然,每个 textarea 都需要不同的 ID(因为我计划将其发送到 API),所以我在主控制器的范围内创建了一个 stageIndex 变量。然后在我的新阶段指令中,我将其添加到父 div 与另一个 textarea 与 stageIndex 作为 id.... 但它只是出现 NaN 而不是我指定的数字。有任何想法吗? app.controller("admin", function($scope, $location, $http, $state){

app.controller("admin", function($scope, $location, $http, $state){
    $scope.stageIndex = 0;
    // My other code here
});

app.directive('newstage', function(){ // This is my buttons directive, hence the element.click()
    return function(scope, element, attrs){
        element.click(function($scope){
            $scope.stageIndex += 1;
            element.parent().append("<textarea ng-attr-id="+ 'stage-' + $scope.stageIndex +"></textarea>");
        });
    }
});

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您提供给 click 的回调不是用$scope 调用的,也没有在那里执行依赖注入。将$scope.stageIndex += 1; 替换为scope.stageIndex += 1;。

    点击函数来自jQuery:http://api.jquery.com/click/

    app.controller("admin", function($scope, $location, $http, $state){
        $scope.stageIndex = 0;
        // My other code here
    });
    
    app.directive('newstage', function(){ // This is my buttons directive, hence the element.click()
        return function(scope, element, attrs){
            //element.click(function($scope){ // $scope is undefined here!!!
            // I would prefer do the following as it does not require jQuery and will work with jqLite
            element.on('click', function () {
                // use scope:
                scope.stageIndex += 1;
                element.parent().append("<textarea ng-attr-id="+ 'stage-' + $scope.stageIndex +"></textarea>");
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多