简体   繁体   中英

Setting a new property on an object in an Angular directive for use in the controller

I have a directive that is populating a div . It takes in a object, does some logic to figure out a variable, inserts the variable into the template and returns the template to the div .

How can I set a new property on the object and pass it back to the controller for use?

For example: HTML:

<div node-icon node="node"></div>

Object going in

{ name: 'Apple',
  count: 5,
  price: '$5'
}

Directive Logic

.directive('nodeName', [function () {
  return {
    restrict: 'A',
    scope: {node: '='},
    template: '<span ng-bind-html="color"></span>',

    link: function ($scope) {
      if(node.name === 'Apple') {
        $scope.color = 'red';
      }
    }
  };
}])

I want to pass the object back to the controller looking like this

{ name: 'Apple',
  count: 5,
  price: '$5',
  color: 'red'
}

If you are sending the object in with scope: {node: '='}, just use scope.node and append the property (it's javascript, it will work).

The link function declaration is wrong , though.

link: function link(scope, element, attrs) { {
  if(scope.node.name === 'Apple') {
    scope.node.color = 'red';
  }
} 

Hope it helps

The scope: {node: '='} means there is a two-way binding between the variable of the host scope (the scope in which the directive is used) that is passed in the node attribute, and the node variable in the directive's own scope. Therefore in the link function, you can read and write scope.node and the changes will be reflected in the host scope.

link: function (scope) {
    if(scope.node.name === 'Apple') {
        scope.node.color = 'red';
    }
}

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