AngularJS:在指令控制器的回调中使用ViewModel-Variables

AngularJS: Using ViewModel-Variables in Callback of Directive-Controller

本文关键字:ViewModel-Variables 回调 指令控制器 AngularJS      更新时间:2023-09-26

我试图用控制器构建一个指令,该控制器更新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();
                });
            };
        }]
    };
});