AngularJS:在指令控制器的回调中使用ViewModel-Variables
AngularJS: Using ViewModel-Variables in Callback of Directive-Controller
我试图用控制器构建一个指令,该控制器更新viewmodel变量并调用回调函数。在回调函数中,应该使用更新后的变量,但它仍然得到旧的值。
HTML:<div ng-app="app" ng-controller="AppCtrl">
Var: {{vm.var}}
<ng-element var="vm.var" func="vm.func()"></ng-element>
</div>
JavaScript: var app = angular.module('app', []);
app.controller('AppCtrl', function($scope) {
$scope.vm = {
var: 'One',
func: function() {
alert($scope.vm.var);
}
};
});
app.directive('ngElement', function(){
return {
restrict: 'E',
scope: true,
bindToController: {
var: '=',
func: '&'
},
controllerAs: 'ctrl',
replace: true,
template: '<button ng-click="ctrl.doIt()">Do it</button>',
controller: function() {
this.doIt = function() {
this.var = 'Two';
this.func();
};
}
};
});
所以当点击按钮时,调用doIt(),更新var并调用func()。但是当func()执行时,var仍然得到旧值"One"。在执行后,ViewModel得到更新,值为"Two"。
在执行函数之前是否有任何方法来更新ViewModel ?
JSFiddle
不确定你的指令在做什么,因为我从来没有使用过bindToController,但这似乎是有效的:
directive('ngElement', function () {
return {
restrict: 'E',
scope: {
var: '=',
func: '&'
},
replace: true,
template: '<button ng-click="doIt()">Do it</button>',
controller: ['$scope', '$timeout', function($scope, $timeout) {
$scope.doIt = function() {
$scope.var = 'Two';
$timeout(function () {
$scope.func();
});
};
}]
};
});
相关文章:
- 如何在我传递给视图的ViewModel集合中获得jQuery可选对象的值,以作为有序列表进行迭代
- 在Knockout中进行ajax调用后,ViewModel不会更新
- '型号'和'ViewModel'在Knockout.js中
- Javascript SPA ViewModel Refactoring
- 将MVC ViewModel转换为外部.js文件中的Javascript对象
- 无法读取属性'来自JS'外部viewmodel.js中未定义的
- KnockoutJS - ViewModel (祖父 - 父 - 子)访问子元素中的父函数
- Javascript ViewModel Initialisation
- viewModel 使用挖空.js在原型上计算函数
- 使用KnockoutJS,如何指定要绑定到的ViewModel
- 获取 ViewModel 绑定到 HTML 元素 Kendo UI MVVM
- 创建一个 KnockoutJS ViewModel,使用 post 命令来填充 ViewModel
- 在外部JavaScript文件中使用KnockoutJS ViewModel
- 当我调用“viewModel.errors().length”时,会触发假错误消息
- Javascript JSON 解析从 MVC 中的 ViewModel “意外令牌 &”
- 将强类型的 ViewModel 值传递给 Javascript 函数
- 挖空.js数据绑定到 ViewModel
- 使用KnockoutJS进行嵌套Viewmodel If Binding
- Knockout:在绑定到ViewModel函数的渲染内容中创建链接的最佳方法
- KnockoutJS-重新绑定ViewModel