Skip to content

Instantly share code, notes, and snippets.

@kneerunjun
Last active November 28, 2015 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kneerunjun/ddf40ef8aadd0451c3a5 to your computer and use it in GitHub Desktop.
Save kneerunjun/ddf40ef8aadd0451c3a5 to your computer and use it in GitHub Desktop.
describes how one would have to use the eval in gettin literal boolean values bound on scope

Faultline

Simple isolated scope directive fails to bind the literal boolean value from the attributes to the scope. This is un-intuitive.

<body ng-app="myApp" ng-controller="mainController">
  <my-directive visibility='true'></my-directive>
</body>
//and here is the definition of the application and the directive
var myApp = angular.module("myApp", [])
.directive("myDirective", function(){
  return{
    restrict:"E",
    scope:{
      visibility:"=" //very odd this does not link on the scope
    },
    controller:function($scope){
      //would print 'true' as a string and woudl not actually get the actual bool value
      console.log("the value we have linked here is " + $scope.visibility) 
      
    }
  }
})

solution

$eval can solve the trouble

<body ng-app="myApp" ng-controller="mainController">
  <my-directive visibility='true'></my-directive>
</body>
//and here is the definition of the application and the directive
var myApp = angular.module("myApp", [])
.directive("myDirective", function(){
  return{
    restrict:"E",
    scope:{},
    link:function(scope, elem, attrs){
      //well just go ahead to roll up the code yourself
      scope.visibility  = scope.$eval($(elem[0]).attr("visibility"));
    }
    controller:function($scope){
      //and boom this is perfectly linked now. prints the bool value on the console
      console.log("the value we have linked here is " + $scope.visibility) 
      
    }
  }
})
<body ng-app="myApp" ng-controller="mainController">
  <my-directive visibility='flag'></my-directive>
</body>
//and here is the definition of the application and the directive
var myApp = angular.module("myApp", [])
.controller("mainController", function($scope){
  $scope.flag = true;
})
.directive("myDirective", function(){
  return{
    restrict:"E",
    scope:{
      visibility:"="
    },
    controller:function($scope){
      //and boom this is perfectly linked now. prints the bool value on the console
      console.log("the value we have linked here is " + $scope.visibility) 
    }
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment