Accessing the same variable in a directive and controller in AngularJS

A few days ago, I was working with this type of structure in AngularJS:

<div class='container' ng-controller='formController'>
  ...some stuff...
  <content-tag-buttons></content-tag-buttons>
</div>

I had a directive, contentTagButtons inside of an Angular controller, which was pretty basic.  I needed to be able to assign a value to a variable in the contentTagButtons directive, but still have access to it in formController. This is where directive scope comes in handy.

In my directive:

var app = angular.module("myApp", []);

app.directive("contentTagButtons", function() {
  return {
    restrict: "E",
    scope: false, // the important part
    link: function($scope, element, attrs) {
      $scope.someSharedVar = "bikes are cool";
    }
  }
})

 

For my purposes when I set the scope attribute to false, the directive uses its parent scope. This means that $scope.someSharedVar my contentTagButtons directive  would be the same as $scope.someSharedVar in my formController controller.

Shidhin explains directive scoping in more detail in his post here.

Concatenate an array in JavaScript

I’ve been slacking off on the food-related posts lately because of my day job. Then it occurred to me that I started this blog as a general repository of things that interest me, even non-food things. I read a recent article about how productive StackOverflow has made developers because they no longer have to RTFM. I know I have found a lot of value in googling bugs in my code.  In an effort to contribute to the interweb knowledge base, I’m going to try to post a couple of short blogs each week with tips I’ve learned while developing, no matter how elementary they could be.  Who knows, maybe someone else will save some time by stumbling on these posts.

Recently, I’ve been needing to concatenate arrays in JavaScript.  Using the concat() method is tricky because concatenating one array into the other creates a new array instead of altering the original array:

arr = [1,2,3]
>> [1, 2, 3]
arr2 = [4,5,6]
>> [4, 5, 6]
arr.concat(arr2)
>> [1, 2, 3, 4, 5, 6]
arr
>> [1, 2, 3]

 

The above isn’t exactly what I wanted, so I’ve been doing this instead, which lets me concat an array into the first array, altering the first array:

arr
>> [1, 2, 3]
arr2
>> [4, 5, 6]
Array.prototype.push.apply(arr, arr2)
>> 6
arr
>> [1, 2, 3, 4, 5, 6]