在将object与属性一起使用时,从指令中获取ngModel的值

时间:2013-11-14 07:10:39

标签: angularjs

不确定如何对问题进行说明,请编辑,如果您能提出更好的建议。我有以下指令:

app.directive('foo', function() {
    return {        
        restrict: 'A',
        require: "?ngModel",
        link: function (scope, element, attrs, controller) {
            scope.$watch(attrs.ngModel, function () {
                console.log("Changed to " + scope[attrs.ngModel]);
            });
        }
    };
});

当我拥有它时效果很好并且正确记录

<input type="text" ng-model="bar" />

app.controller('fooController', function($scope) { 
    $scope.bar = 'ice cream';
});

当我以这种方式尝试时,它不起作用。它会记录“已更改为未定义”

<input type="text" ng-model="model.bar" />

app.controller('fooController', function($scope) { 
    $scope.model = { bar: 'ice cream' };
});

如何使其适用于这两种情况。看起来正确的角度可以让你使用两者。

2 个答案:

答案 0 :(得分:11)

我查看了ngModel指令,发现了一个名为ngModelGet的函数。使用$ parse。

app.directive('foo', function($parse) {
    return {        
        restrict: 'A',
        require: "?ngModel",
        link: function (scope, element, attrs, controller) {
            var ngModelGet = $parse(attrs.ngModel);

            scope.$watch(attrs.ngModel, function () {
                console.log("Changed to " + ngModelGet(scope));
            });
        }
    };
});

答案 1 :(得分:5)

你可以使用

var ngModelCtrl = controller;
ngModelCtrl.$viewValue

替换

scope[attrs.ngModel]

这里是ngModelCtrl sdk

相关问题