Reputation: 29576
I have a directive:
app.directive('mydirective', function () {
return {
scope: {
field: '='
},
require: 'ngModel',
link: function (scope, element, attrs, contr) {
contr.$parsers.unshift(function (value) {
console.log(scope.mymodel);
});
}
}
});
and I have a form that uses the directive
<form ng-submit="submit()">
<input type="text" ng-model="mymodel" mydirective field="123" />
<div>{{mymodel}}</div>
</form>
the model of the input
element is set to mymodel
. Under the input
I would like to display the value of this model.
The problem is that the value {{mymodel}}
is not rendered. And it seems that mymodel
in the current $scope
never changes as I type in the input
field.
I thought that this is because the directive creates another scope, but console.log(scope.mymodel)
inside the link
function outputs undefined
as well.
Without mydirective
in input
I can see the model's value under the field with no problems.
Could someone please explain where the model is kept? Which scope is it in?
the live code:
Upvotes: 0
Views: 255
Reputation: 54659
Two things:
As Chandermani wrote, you're introducing a new scope with scope: { field: '=' },
on the input. Thus you'll need to reference mymodel
as ng-model="$parent.mymodel"
or angular will look on the wrong scope.
<input type="text" ng-model="$parent.mymodel" mydirective field="123" />
$parsers
should return a value, otherwise the parser chain is broken.
ctrl.$parsers.unshift(function (value) {
console.log(value);
return value; // <- add this
});
Fixed code (excuse the restructuring ;)):
(function (app, ng) {
app.controller('MyCtrl', ['$scope', function ($scope) {
$scope.submit = function submit() {
console.log('submit');
};
}]);
app.directive('mydirective', function () {
return {
require: 'ngModel',
scope: { field: '=' },
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (value) {
console.log(value);
return value; // <- add this
});
}
};
});
}(angular.module('myapp', []), angular));
demo: http://jsbin.com/uzixey/1/
Upvotes: 1
Reputation: 42669
Since you have created a scope object in directive definition, it creates an isolated scope which does not inherit from the parent scope. ng-model and isolated scope do not work well. See this from SO
Upvotes: 1