Question

Having a following template in templateUrl:

<input name="foo" ng-model="test">

directive:

app
  .directive('bar', function() {
    return {
      link: function link(scope, element, attrs, ctrl) {
        scope.$watch(scope.test, function(newVal) {
          console.log(val);
        });
      },
      restrict: 'E',
      templateUrl: 'templates/foo.html'
    };
   });

can I two-way bind it in directive so I scope.$watch input variable? I tried using ng-bind and ng-model, but I cannot access that variable in scope of my directive.

Edit Added directive code.

Était-ce utile?

La solution

Change:

scope.$watch(scope.test, ...

to

scope.$watch('test', ...

and it should work. The first argument to $watch is the (so called) watchExpression. It will be evaluated against the relevant scope. When using a string you can basically use everything you would also use in the views/templates.

Mind that this will break again if you start using isolated scopes.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top