Javascript AngularJS:在指令控制器的回调中使用ViewModel变量
我试图用一个控制器构建一个指令,它更新一个ViewModel变量并调用一个回调函数。在回调函数中,应该使用更新的变量,但它仍然得到旧值 HTML:Javascript AngularJS:在指令控制器的回调中使用ViewModel变量,javascript,angularjs,angular-directive,Javascript,Angularjs,Angular Directive,我试图用一个控制器构建一个指令,它更新一个ViewModel变量并调用一个回调函数。在回调函数中,应该使用更新的变量,但它仍然得到旧值 HTML: Var:{{vm.Var} JavaScript: var app = angular.module('app', []); app.controller('AppCtrl', function($scope) { $scope.vm = { var: 'One', func: function() {
Var:{{vm.Var}
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();
};
}
};
});
var-app=angular.module('app',[]);
app.controller('AppCtrl',函数($scope){
$scope.vm={
变量:“一”,
func:function(){
警报($scope.vm.var);
}
};
});
应用指令('ngElement',函数(){
返回{
限制:'E',
范围:正确,
bindToController:{
变量:'=',
func:“&”
},
controllerAs:'ctrl',
替换:正确,
模板:“做它”,
控制器:函数(){
this.doIt=函数(){
this.var='Two';
this.func();
};
}
};
});
因此,当单击按钮时,doIt()调用,更新var并调用func()。但是当执行func()时,var仍然得到旧值“One”。执行后ViewModel立即更新,值为“2”
在执行函数之前,是否有任何方法更新ViewModel
不确定您的指令到底在做什么,因为我从未使用过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();
});
};
}]
};
});
指令('ngElement',函数(){
返回{
限制:'E',
范围:{
变量:'=',
func:“&”
},
替换:正确,
模板:“做它”,
控制器:['$scope','$timeout',函数($scope,$timeout){
$scope.doIt=function(){
$scope.var='Two';
$timeout(函数(){
$scope.func();
});
};
}]
};
});
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();
});
};
}]
};
});