Skip to content

Instantly share code, notes, and snippets.

@pc035860
Created March 9, 2014 16:11
Show Gist options
  • Save pc035860/9450018 to your computer and use it in GitHub Desktop.
Save pc035860/9450018 to your computer and use it in GitHub Desktop.
Attach a new helper function "$glance" to scope. Enables complex conditional scope one-time observation.
angular.module('scope.glance', [])
.factory('attach$glance', ['$q', function ($q) {
function $glance(watchExpression, checkFunction, objectEquality) {
var scope = this;
var dfd = $q.defer(),
clearWatch;
checkFunction = checkFunction || function (newVal, oldVal, scope) {
return !!newVal;
};
clearWatch = scope.$watch(watchExpression, function () {
var args = Array.prototype.slice.call(arguments),
res = checkFunction.apply(this, args);
if (res) {
dfd.resolve(args);
clearWatch();
}
}, objectEquality);
return dfd.promise;
}
return function (scope, name) {
name = name || '$glance';
scope[name] = $glance;
};
}]);
@pc035860
Copy link
Author

pc035860 commented Mar 9, 2014

Example

angular.module('myApp', ['scope.glance'])

.run(function (attach$glance, $rootScope) {
  attach$glance($rootScope);
})

.controller('MainCtrl', function MainCtrl($scope, $q) {

  // Retrieval time varies
  $scope.dataA = retrieveDataFrom('A');
  $scope.dataB = retreiveDataFrom('B');

  $q.all([
    $scope.glance('dataA.init'),
    $scope.glance('dataB.init', function (newVal, oldVal) {
      // Resolve condition
      return (newVal === 'foo');
    })
  ])
  .then(function () {
    // Initialization ready
  });

  function retreiveDataFrom(remote) {
    // Retrieve some data
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment