Skip to content

Instantly share code, notes, and snippets.

@kurtfunai
Last active August 29, 2015 14:01
Show Gist options
  • Save kurtfunai/07d7a3f0ff18eb558965 to your computer and use it in GitHub Desktop.
Save kurtfunai/07d7a3f0ff18eb558965 to your computer and use it in GitHub Desktop.
Angular ng-init vs directive
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MyCtrl" ng-init="myValue = 'blah';"></div>
<my-directive my-value="hallo world!"></my-directive>
</body>
</html>
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
// myValue will be undefined in console
console.log($scope.myValue);
angular.element(document).ready(function() {
// $scope.myValue is only set after this fires
});
})
.directive('myDirective', function() {
return {
restrict: "E",
scope: {
myValue: "@"
},
link: function($scope, ele, attrs){
// myValue is set immediately
console.log($scope.myValue);
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment