简体   繁体   中英

Binding text inputs to a directives attribute

I'm trying to bind a text input to an attribute within a directive, the reason being I don't want to have to introduce a controller each time I add a new directive of this type. Is this even possible or do you always have to specify a controller when using ng-model. Code example is worth a thousand words so please take a look at http://codepen.io/scottwio/pen/HKqiw . As you type in the input the amount should change.

There are two issues with your code:

  1. scope.$watch(attrs.amount, function (v) {...}); <=>
    scope.$watch('100', function (v) {...});
    which is never going to change, so does not do what you want.

  2. Since the elements attribute is never going to change, function draw(aniTime) { var amount = attrs.amount; is not so usefull.


You can fix them like this:

scope.$watch('amount', function (v) {...});

and

function draw(aniTime) {
    var amount = scope.amount;
    ...

See, also, this short demo .


If you want to share the specified amount with the parent scope, then you need to set up a two-way data-binding and specify a property in the parent scope to bind to. Eg:

// Parent scope
$scope.someAmount = 100;

// In HTML
<custommarc amount="someAmount" ...

// In directive
scope: {
    amount: '='
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM