Angular Directive函数调用ng-change

时间:2014-11-20 15:55:29

标签: angularjs angularjs-directive angularjs-bootstrap

我有一个angular-bootstrap模式弹出框,其中包含模板中的自定义指令:

Modal.html

<div class="modal-header">
    <h3 class="modal-title">Modal Header</h3>
</div>
<div class="modal-body">
    <div class="row">
        <div class="col-md-12">
            <my-directive ng-model="test" ng-change="doSomething()" />
        </div>
    </div>
</div>
<div class="modal-footer">
    <button class="btn btn-primary" ng-click="upload()">Upload</button>
    <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>

ModalCtrl.js

app.controller('ModalCtrl', function ModalCtrl( $scope, $modalInstance ) {
    $scope.test = 'empty';

    $scope.upload = function() {
        $scope.test = 'change!';
    };

    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

我从我的主控制器打开模态弹出窗口,如下所示:

MainCtrl.js

var app = angular.module( 'myApp', [ 'ui.bootstrap' ] );

app.controller('MainCtrl', function MainCtrl( $scope, $modal ) {
    $scope.openModal = function() {
        var modalInstance = $modal.open({
            templateUrl: '/assets/modals/Modal.html',
            controller: 'ModalCtrl',
            size: 'md'
        });
    };
});

从上面的代码中可以看出,模态模板包含我的自定义指令<my-directive>,它采用$scope.test - 在ModalCtrl中定义 - 作为它的模型,应该当该模型发生变化时,请致电$scope.doSomething()

自定义指令如下所示:

MyDirective.js

angular.module( 'myApp' ).directive( 'myDirective', function() {
    return {
        controller: function( $scope ) {
            $scope.doSomething = function() {
                console.log( 'doSomething() called! $scope.test now = ' + $scope.test );
            };
        },

        link: function( $scope, el, att ) {
            console.log( '$scope.test = ' + $scope.test );
        },

        template: '<div class="thumbnail"></div>'
    };
} );

当模态弹出窗口打开时,控制台会打印出$scope.test = empty,这正是我期望看到的。但是通过调用$scope.test中的$scope.upload()函数来更改ModalCtrl时,没有任何反应!我认为应该发生$scope.doSomething()被调用,然后应该在控制台doSomething() called! $scope.test now = change!中打印出来。

任何帮助都会非常感激,这让我很生气!

1 个答案:

答案 0 :(得分:1)

我明白了。我没有使用ng-model和ng-change,而是添加了:

scope: {
    test: '@'
}

到我的指令并将其添加到我的链接功能中:

$scope.$watch( 'test', function() { 
    console.log( 'test changed' ); 
} );

然后我将test作为参数添加到我的指令标签中,如下所示:

<my-directive test="test" />

最后每当我更改$ scope.test时,我都会调用$scope.$apply()并瞧!