gpt4 book ai didi

javascript - 在指令中调用时,Angular JS Controller 元素未定义

转载 作者:行者123 更新时间:2023-12-01 02:48:49 24 4
gpt4 key购买 nike

我有一个像这样的 Controller :

myApp.controller('WizardController', function ($scope, $http) {

$scope.user = {
addressline1: null,
cobuyer: null,
validate: null,
cobuyerfirstname: null,
cobuyerlastname: null,
cobuyeremail: null,
cobuyerdob: null,
cobuyeraddressline1: null,
cobuyeraddressline2: null,
cobuyercity: null,
cobuyerprovince: null,
cobuyerpostalcode: null,
cobuyerphone: null,
dobString: null,
cobuyerDobString: null,
isWaitList: false
};

});

我在下面添加了这个指令:

myApp.directive('checkbox', function () {
return {
restrict: 'A',
replace: false,
transclude: true,
scope: {
user: '='
},
template: '<label for="addressSame" class="form-label col-md-2" style="width: auto;">Same as Buyers Address</label><input type="checkbox" name="addressSame" ng-click="isSameAddress()" ng-model="isChecked" />',
link: function (scope, element, attrs) {
// Initialize to unchecked
scope.isChecked = false;

},
controller: function ($scope) {

$scope.isSameAddress = function () {

console.log($scope.isChecked);

if ($scope.isChecked == true) {
console.log($scope.user);
}
else {

}
}

}
}
});

现在我的复选框按其应有的方式显示,我可以检查它并从scope.isChecked 获取 true 或 false。我现在尝试从 $scope.user 获取项目,但它说它未定义。我对 Angular JS 相当陌生,我不知道如何解决这个问题...我如何获取 Controller 中定义的元素?

我也尝试过这个,仍然未定义:

myApp.directive('checkbox', function () {
return {
restrict: 'A',
replace: false,
transclude: true,
scope: {
user: '='
},
template: '<label for="addressSame" class="form-label col-md-2" style="width: auto;">Same as Buyers Address</label><input type="checkbox" name="addressSame" ng-click="isSameAddress()" ng-model="isChecked" />',
link: function (scope, element, attrs) {
// Initialize to unchecked
scope.isChecked = false;

},
controller: function ($scope, $http, $rootScope) {

$scope.isSameAddress = function () {

console.log($scope.isChecked);

if ($scope.isChecked == true) {
console.log($rootScope.user);
}
else {

}
}

}
}
});

最佳答案

这是因为 $scope 仅在 Controller 本身内部可见;您可以使用 $rootScope (只需记住它是一个全局变量);尝试从 $scope.user 更改为 $rootScope.user

关于javascript - 在指令中调用时,Angular JS Controller 元素未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47099373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com