[英]How to ensure that a scope variable updates and binds before going to view angularjs
[英]AngularJS Make a scope variable available before view is loaded
我正在創建一組選擇框,這些選擇框使用div上帶有選擇標記的指令綁定到視圖中的值列表。 它們填充了一些值,但是在渲染它們之后,我想根據已存儲的值來設置一個值。
我正在嘗試通過使用我在控制器中調用的函數(在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 initializeSelects()
調用中,沒有看到我在作用域調用中設置的變量來retrieveSetValues()
resetSetValues initializeSelects()
。
我嘗試了兩種方法,都在控制器中調用它,並在嘗試訪問initializeSelects()
的保存值之前從ng-init
調用它。
我是新手,對整個摘要周期的工作方式的理解是新手。 :(
任何幫助表示贊賞!
您也可以嘗試:
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它將在您的控制器中。
我為此創建了一個小提琴, 在這里檢查
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.