如何观察指令的指令ng模型

时间:2014-04-02 18:04:38

标签: javascript angularjs angularjs-directive angularjs-scope angular-ngmodel

我有一个在该视图中使用父作用域的指令。该指令有一个使用隔离范围的子指令。我试图让父指令观察对子指令的ngModel所做的任何更改,并在更改时更新自己的模态。这是一个可能更好解释的jsfiddle:http://jsfiddle.net/Alien_time/CnDKN/

以下是代码:

   <div ng-app="app">
        <div ng-controller="MyController">

            <form name="someForm">
                <div this-directive ng-model="theModel"></div>
            </form>

         </div>
    </div>

使用Javascript:

    var app = angular.module('app', []);
app.controller('MyController', function() {

});

app.directive('thisDirective', function($compile, $timeout) {

    return {
        scope: false,

        link: function(scope, element, attrs) {
            var ngModel = attrs.ngModel;
            var htmlText = '<input type="text" ng-model="'+ ngModel + '" />' +
                           '<div child-directive ng-model="'+ ngModel + '"></div>';

            $compile(htmlText)(scope, function(_element, _scope) {
                element.replaceWith(_element);                
            });

            // Not sure how to watch changes in childDirective's ngModel ???????

        }, // end link
    } // end return

});

app.directive('childDirective', function($compile, $timeout) {
    return {
            scope: {
                ngModel: '='            
        },  

        link: function(scope, element, attrs, ngModel) {
            var htmlText = '<input type="text" ng-model="ngModel" />';

            $compile(htmlText)(scope, function(_element, _scope) {
                element.replaceWith(_element);                
            });   

            // Here the directive text field updates after some server side process
            scope.ngModel = scope.dbInsertId;

            scope.$watch('dbInsertId', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");  // Delete this later
                    scope.ngModel = scope.imageId;
            }, true);

        },

    } // end return
});

在该示例中,您可以看到父指令内的文本输入及其子指令。如果您在每个模型中输入内容,则另一个模型会更新,因为它们被ngmodel绑定。但是,子指令的文本输入在服务器连接后会更新。发生这种情况时,父指令中的文本输入不会更新。所以我想我需要在子指令中观察ngModel以进行任何更改。 我该怎么做?这有意义吗?

1 个答案:

答案 0 :(得分:13)

正如@shaunhusain所提到的,你必须使用ngModelController与ngModel进行交互。在ngModelController上,您可以在$modelValue上设置监视,并且可以通过调用$setViewValue来更改模型中的值。请记住,要使用ngModelController,您需要在指令定义对象中添加require: "ngModel"

当您从angular之外获取一个值(比如从数据库中获取)并且您又想要使用该值来更改模型值时,您需要将该代码包装在scope.$apply()

app.directive('thisDirective', function($compile, $timeout, $log) {

    return {
        scope: false,
        require: 'ngModel',

        link: function(scope, element, attrs, ngModel) {
            ...

            scope.$watch(
                function(){
                    return ngModel.$modelValue;
                }, function(newValue, oldValue){
                    $log.info('in *thisDirective* model value changed...', newValue, oldValue);
                }, true);

        }, // end link
    } // end return

});

app.directive('childDirective', function($compile, $timeout, $log) {
    return {
        scope: {
            ngModel: '='
        },
        require: 'ngModel',

        link: function(scope, element, attrs, ngModel) {
            ...

            scope.$watch(
                function(){
                    return ngModel.$modelValue;
                }, function(newValue, oldValue){
                    $log.info('in *childDirective* model value changed...', newValue, oldValue);
                }, true);

            // make believe change by server
            setTimeout(function() {
                scope.$apply(function() {
                    ngModel.$setViewValue('set from the server...');
                };
            },5000);


        },

    } // end return
});

相关的jsfiddle http://jsfiddle.net/CnDKN/2/

但是我认为这不是$setViewValue的正确用法。根据文档,这应该用于更新UI上显示的值,而不一定是模型值。

实际上有另一种方法可以使这项工作更简单易用。只需使用=attr设置要在thisDirectivechildDirective中使用的属性的双向绑定。然后你可以在你的指令中设置ng-model属性设置,当你第一次使用它时,你甚至不需要知道它在下面使用了ng-model。

以下代码向您展示我的意思:

app.directive('thisDirective', function($compile, $timeout, $log) {

    return {
        scope: {
            thisval: '='
        },

        link: function(scope, element, attrs) {

            var htmlText = '<input type="text" ng-model="thisval" />' +
                           '<div child-directive childval="thisval"></div>';

            $compile(htmlText)(scope, function(_element, _scope) {
                element.replaceWith(_element);                
            });

            scope.$watch('thisval',function(newVal,oldVal){
                $log.info('in *thisDirective* thisval changed...',
                          newVal, oldVal);
            });


        }, // end link
    } // end return

});

app.directive('childDirective', function($compile, $timeout, $log) {
    return {
        scope: {
            childval: '='
        },

        link: function(scope, element, attrs) {
            var htmlText = '<input type="text" ng-model="childval" />';

            $compile(htmlText)(scope, function(_element, _scope) {
                element.replaceWith(_element);                
            });

            scope.$watch('childval',function(newVal,oldVal){
                $log.info('in *childDirective* childval changed...',
                          newVal, oldVal);
            });

            // make believe change that gets called outside of angular
            setTimeout(function() {
                // need to wrap the setting of values in the scope 
                // inside of an $apply so that a digest cycle will be 
                // started and have all of the watches on the value called
                scope.$apply(function(){
                    scope.childval = "set outside of angular...";
                });
            },5000);

        },

    } // end return
});

更新了jsfiddle示例:http://jsfiddle.net/CnDKN/3/