0

I have a directive named dir with:

ng-model="job.start_date"

comparison-date="job.end_date

Into scope.$watch("comparisonDate... I want to access my ng-model value. The problem is that scope is undefined into watch's callback function. The Question is: How can I get the ng-value inside this function?

.directive("dir", function() {
    return {
        scope: {
            comparisonDate: "=",
            ngModel: "="
        },

        link: function (scope, element, attrs, ctrl) {
            var foo = scope.ngModel;
            scope.$watch("comparisonDate", function(value, oldValue) {
                console.log(value); //comparisonDate showing value properly
                console.log(scope.ngModel); //Undefined
                    console.log(foo) //shows value but it's not refreshing. It shows allways the initial value
            })
        }
    };
})

the view...

<input dir type="text" ng-model="job.start_date" comparison-date="job.end_date"/>
4

3 回答 3

1

在指令的链接阶段,该值可能不可用。您可以使用$observe来观察值的变化。

attrs.$observe("comparisonDate", function(a) {
    console.log(scope.ngModel);
})
于 2013-09-27T18:07:52.533 回答
1

ng-model是告诉 Angular 进行双向数据绑定的内置指令。http://docs.angularjs.org/api/ng.directive:ngModel

看起来您正在使用同一对象的属性值job进行比较。如果你想坚持ng-model,你可以使用NgModelControllerhttp ://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

然后将视图更改为:

<input dir type="text" ng-model="job"/>

并将指令更改为:

.directive("dir", function() {
    return {
        require: '?ngModel', // get a hold of NgModelController
        link: function (scope, element, attrs, ngModel) {
            // access the job object
            ngModel.$formatters.push(function(job){
                console.log(job.start_date);
                console.log(job.end_date);
            });
        }
    };
})

或者您可以将属性名称从更改ng-model为一些未保留的单词。例如更改视图,如:

<input dir type="text" comparison-start-date="job.start_date" comparison-end-date="job.end_date"/>
于 2013-09-27T20:59:37.433 回答
0

尝试scope.$watch(attrs.comparisonDate, ...)然后使用attrs.ngModel

于 2013-09-27T17:32:34.900 回答