![](/img/trans.png)
[英]Proper way to pass complex variables to javascript through HTML
[英]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
功能的分配。
ng-model
,則在觸發ng-change
函數時,請嘗試將作為傳遞參數的新值保存在$scope
以便跨該控制器中的所有其他函數訪問它。 ng-model
,則只需將ng-model的屬性用作參考變量。 例如: ng-model="xyz"
然后$scope.xyz
將為您提供所需的元素值。 這樣可以相應地訪問元素值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.