AngularJS - 如何改变ngModel的自定义配置参数的值? [英] AngularJS - how to change the value of ngModel in custom directive?

查看:475
本文介绍了AngularJS - 如何改变ngModel的自定义配置参数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看看我的指令:

angular.module('main').directive('datepicker', [
function() {
    return {
        require: '?ngModel',
        link: function(scope, element, attributes, ngModel) {
            ngModel.$modelValue = 'abc'; // this does not work
            // how do I change the value of the model?

那么,我该如何改变NG-模型的价值?

So, how do I change the value of the ng-model?

推荐答案

要处理复杂的结合前pressions工作,你应该使用的 $解析服务和分配方法。

To work with complex binding expressions you should use the $parse service and the assign method.

有关详细信息,观看NG-conf的此视频 - 这是所有关于很酷的事情,你可以用NG-模型指令做:<一href=\"https://www.youtube.com/watch?v=jVzymluqmg4\">https://www.youtube.com/watch?v=jVzymluqmg4

For more information watch this video from ng-conf - it's all about the cool things you can do with the ng-model directive: https://www.youtube.com/watch?v=jVzymluqmg4

app.directive('datepicker', ['$parse',
    function($parse) {
        return {
            require: '?ngModel',
            link: function(scope, element, attributes, controller) {
                // $parse works out how to get the value.
                // This returns a function that returns the result of your ng-model expression.
                var modelGetter = $parse(attributes['ngModel']);
                console.log(modelGetter(scope));

                // This returns a function that lets us set the value of the ng-model binding expression:
                var modelSetter = modelGetter.assign;

                // This is how you can use it to set the value 'bar' on the given scope.
                modelSetter(scope, 'bar');

                console.log(modelGetter(scope));
            }
        };
    }
]);

这篇关于AngularJS - 如何改变ngModel的自定义配置参数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆