Javascript 无法访问指令';指令'中的s范围对象;s控制器
MaterialIn.directive.jsJavascript 无法访问指令';指令'中的s范围对象;s控制器,javascript,angularjs,angularjs-directive,controller,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Controller,Angularjs Scope,MaterialIn.directive.js angular.module('mdt') .directive('mdtMaterialins', materialInsDirective); function materialInsDirective() { return { restrict: 'E', scope: { materialoffers: '=', }, bindToC
angular.module('mdt')
.directive('mdtMaterialins', materialInsDirective);
function materialInsDirective() {
return {
restrict: 'E',
scope: {
materialoffers: '=',
},
bindToController: true,
templateUrl: 'app/materialOffers/materialIns/materialIns.html',
controllerAs: 'materialInsVm',
controller: MaterialinsController
};
}
function MaterialinsController($scope) {
var vm = this;
console.log(vm); //shows the materialoffers object present
console.log(vm.materialoffers); //show undefined
}
大家好。我做了一个指令并向它发送了一个对象数组“materialoffers”,我可以在html页面上访问它。它工作正常,但idk为什么我不能在控制器内访问它,它显示未定义,有人能告诉我一种在控制器内使用materialoffers的方法吗,我想得到它的长度并将其存储在$scope变量中,如下所示
vm.total=vm.materialoffers.length;
似乎
materialoffers
变量可能在$http调用或类似调用后获得其值,因为在创建指令时,它不会立即具有值。console.log(vm)
显示变量,因为当您单击它时,它会显示对象的状态(在本例中为vm)。您可以在浏览器控制台中使用以下代码测试此现象:
var object = {};
object; // logs the object in console, shows an empty object
window.setTimeout(function() {
object.testValue = "test value"
}, 10000) // After 10 seconds, the object will get the property testValue
如果在10秒之前单击对象,则该对象将不具有该属性,但在10秒之后单击该对象后,将在那里看到添加的属性
尝试用以下代码替换控制器代码:
function MaterialinsController($scope) {
var vm = this;
$scope.$watch(function() { return vm.materialoffers }, function() {
console.log(vm.materialoffers)
});
}
您是如何使用指令的?您是否确认
materialoffers
已在父控制器中设置值?我看不出你的代码有任何问题。是的,我在模板中使用materialoffers,它正在工作,但在控制器中没有定义,尽管当我记录整个控制器(vm)时,它表明有materialoffers,如果答案有助于解决你的问题,请将其标记为选定答案,以便将其视为已解决。我对答案进行了投票,但由于我的声誉不足15,因此无法显示我的意思是通过单击投票按钮下方的复选标记来选择正确的答案,