繁体   English   中英

AngularJS传递变量的正确方法

[英]AngularJS Proper way to pass variables

我想将它们设置为全局,以便可以在整个脚本中使用[color][shape] 我将需要每个人独立更新,但是当我继续添加到站点时,我将需要同时使用两者。 实时预览

  • 示例不起作用: $scope.shapeSelected = response.data[color][shape];
  • 示例确实起作用: $scope.shapeSelected = response.data.blue[shape];

var app = angular.module("computer", ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
    when('/main', {
        controller: 'MainCtrl'
    }).
    otherwise({
        redirectTo: '/main'
    })
}])

.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.colorType = function(color) {
        $http.get('stuff.json').then(function(response) {
            $scope.colorSelected = response.data.type[color];

        });
    }

    $scope.shapeType = function(shape) {
        $http.get('shapes.json').then(function(response) {
            $scope.shapeSelected = response.data[color][shape]; // <--- [color] is not getting pulled in on this function.

            var resultsColorShape = $scope.shapeSelected; // <--- I would like to be able to store this incase i need it later. 
            console.log('resultsColorShape');
        });
    }

}]);

您不必将参数传递给函数。 如果您定义了ng-model="Color" ,则可以在JavaScript代码中使用$scope.Color

更改html:

ng-change="colorType()"

ng-change="shapeType()"

和js可以:

 $scope.colorType = function() {
 $http.get('stuff.json').then(function(response) {
     $scope.colorSelected = response.data.type[$scope.Color];

 });
}

 $scope.shapeType = function() {
     $http.get('shapes.json').then(function(response) {
         $scope.shapeSelected = response.data[$scope.Color][$scope.Shape]; 
     });
 }

如果您的问题是关于在各个函数之间传递变量或正确共享数据,那么这将为您提供帮助。

在您的情况下。 随着ng-change功能的分配。

  1. 如果您没有ng-model ,则在触发ng-change函数时,请尝试将作为传递参数的新值保存在$scope以便跨该控制器中的所有其他函数访问它。
  2. 如果您为元素声明了ng-model ,则只需将ng-model的属性用作参考变量。 例如: ng-model="xyz"然后$scope.xyz将为您提供所需的元素值。

这样可以相应地访问元素值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM