我正在创建一组选择框,它们在视图中使用带有select标记的指令绑定到我的视图中的值列表。它们填充了一些值,但在渲染后我想根据已存储的值设置一个值。
我试图通过在ng-init
中设置模型值来实现这一点,使用我在控制器中调用的函数,该函数使用存储的值初始化数组。
但是,渲染选择框并调用ng-init
时,数组始终未定义。
如果在选择框上调用ng-init
时,如何确保始终设置变量?
angular.module('myapp')
.controller('aclCtrl', function()
{
$scope.retrieveSetValues(id)
{
//.then promise to GET stored values, defined in a factory, sets variable that is accessed in initializeSelects()
}
$scope.retrieveSetValues($scope.myID);
}
查看:
选择指令:
.directive("selector", [
function() {
return {
controller: function() {
this.myValues= ['a', 'b', 'c'];
},
require: 'ngModel',
controllerAs: 'ctrl',
scope: {
'ngModel': '='
},
template: '<select ng-model="innerModel" ng-change="updateInnerModel()" ng-options="v for v in ctrl.myValues"> </select>',
link: function(scope, elem, attrs, ngModelController) {
scope.innerModel = scope.ngModel;
scope.updateInnerModel = function() {
ngModelController.$setViewValue(scope.innerModel);
};
}
};
}
])
问题是我在访问ng-init retrieveSetValues()
调用中没有看到我在initializeSelects()
范围调用中设置的变量。
我尝试过这两种方法,在我尝试访问ng-init
中保存的值之前,在控制器中调用它并从initializeSelects()
调用它。
我是棱角分明的新手,我对整个消化循环如何运作的理解是新手级别。 :(
任何帮助表示赞赏!!
答案 0 :(得分:0)
您也可以尝试:
function selector() {
return {
controller: function() {
this.myValues= ['a', 'b', 'c'];
},
require: 'ngModel',
controllerAs: 'ctrl',
scope: {
'ngModel': '='
},
template: '<select ng-model="ngModel" ng-options="v for v in ctrl.myValues"> </select>',
link: function(scope, elem, attrs, ngModelController) {
}
};
}
HTML视图:
<div selector ng-model="vm.initialValue"></div>
vm.initialValue它将在您的控制器中。
我为此创建了一个小提琴,请检查here
我希望它有所帮助。