【问题标题】:AngularJS: Using ViewModel-Variables in Callback of Directive-ControllerAngularJS:在 Directive-Controller 的回调中使用 ViewModel-Variables
【发布时间】:2015-10-19 21:55:03
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs angular-directive


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-02-19
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-08
      • 2017-05-18
      • 1970-01-01
      相关资源
      最近更新 更多