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

时间:2015-10-19 21:55:04

标签: javascript angularjs angular-directive

我正在尝试使用控制器构建一个指令,该控制器更新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

1 个答案:

答案 0 :(得分:0)

不确定你的指令到底在做什么,因为我从未使用过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();
                });
            };
        }]
    };
});