我正在重构我编写的现有代码(其中充满了 $scope 变量)以遵循一些最佳实践。我尝试使用“this”以及controllerAs语法来代替。我有以下有效的 html:
<div ng-hide="card.VIN == 0" class="col-md-7" id="cardAndInfoContainer">
<list-card card="card"></list-card>
</div>
这是我的指令(只有相关部分,很长):
scope: {
card: '='
},
controller: function ($scope, $controller) {
$scope.card = {
VIN: 25,
status: "fadfda",
image: "",
};
$scope.callServiceFunction = function (id) {
//call function in a service
Service.getInfo(id).then(function (data) {
$scope.card = data;
}, function (err) {
console.log(err);
})
}
},
//controllerAs: 'ctrl',
如何重构代码以遵循上述最佳实践?这是我尝试过但没有成功的方法:
-html 不变 -in 指令 Controller :
controllerAs: 'ctrl',
scope: {
card: '='
},
template: template,
controller: function ($scope, $controller) {
var ctrl = this;
this.card = {
VIN:0,
status: "fadfda",
image: ""
};
this.displayCard = function (id) {
Service.getInfo(id).then(function (data) {
$scope.card = data;
}, function (err) {
console.log(err);
})
}
return ctrl;
}
最佳答案
您离开这里的$scope
:
Service.getInfo(id).then(function (data) {
$scope.card = data;
}, function (err) {
console.log(err);
})
尝试
Service.getInfo(id).then(function (data) {
ctrl.card = data;
}, function (err) {
console.log(err);
});
一个建议是在 Controller 底部实际声明命名函数和变量对象
function displayCard(id) {
Service.getInfo(id).then(function (data) {
$scope.card = data;
}, function (err) {
console.log(err);
})
}
var card = {
VIN:0,
status: "fadfda",
image: ""
};
然后在 Controller 顶部将所有引用绑定(bind)到底部的对象
controller: function ($scope, $controller) {
var ctrl = this;
ctrl.card = card;
ctrl.displayCard = displayCard;
这样做的好处是,您可以轻松地在组件顶部创建一个目录,而所有业务都在下面
关于javascript - 避免 $scope.soup 并在 AngularJS 中使用controllerAs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35000914/