user5277847
user5277847

Reputation: 53

Check if attribute exists in directive

I want to check if an attribute exists in a directive and I don't know how to do that, can anyone help? this is probably simple but I am new to angular

(function() {
'use strict';

angular.module('app').directive('home', home);

var strVar="";
strVar += "<home show-text=vm.text></home>" 

function home() {
return {
        restrict: 'E',
        transclude: true,
        template: strVar,
        scope: {

            showText: "="
        },
        controller: HomeController,
        controllerAs: 'vm',
        bindToController: true
};
};

HomeController.$inject = ['$scope','$rootScope', '$timeout','$sce'];
function HomeController($scope,$rootScope,$timeout,$sce) {
if(vm.showText == “undefined”)
{
//Run some code
}


})();

Upvotes: 1

Views: 2145

Answers (3)

Isaac Weingarten
Isaac Weingarten

Reputation: 1190

on the directive object change the scope object to scope: { showText: "=?" }, the '?' is making an attribute optional, then in the controller check if the attribute exists with angular.isUndefined(vm.showText) or with typeof vm.showText === 'undefined'

for more info check out angular 1.7.x - Error: $compile:nonassign Non-Assignable Expression

Upvotes: 1

Fred Brasil
Fred Brasil

Reputation: 29

I know it is an old question but there is another way to check if attribute exists

if(angular.isDefined(vm.content.title)){ //do something}

Upvotes: 0

ach
ach

Reputation: 6234

if (angular.isUndefined($scope.showText)) {
    //do stuff
});

Upvotes: 1

Related Questions