I didn't try any sample but i think with this code will be work
Magento 2.0.x:
With Magento 2.1.x, please read more info in next to answer.
in your controller:
protected $_evaSetup;
public function __construct(.....,
\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
){
parent::__construct($context);
.....
$this->_abc = $eavSetupFactory;
}
public function execute(){
$categorySetup = $this->_evaSetup->create(['setup' => $setup]);
/**
* Add attributes to the eav/attribute
*/
$entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Category::ENTITY);
$attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId);
$categorySetup->addAttribute(
\Magento\Catalog\Model\Category::ENTITY, 'my_attribute', [
'type' => 'int',
'label' => 'My Atrribute ',
'input' => 'select',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
'required' => false,
'sort_order' => 100,
'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
'group' => 'General Information',
]);
$idg = $categorySetup->getAttributeGroupId($entityTypeId, attributeSetId, 'General Information');
$categorySetup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$idg,
'my_attribute',
46);
}
http://www.ibnab.com/en/blog/magento-2/magento-2-add-custom-eav-attribute-to-category-or-customer