angularjs - pass data through attribute in a directive to access it in compile phase? -
is there way access object in directive @ compile phase. since compile phase not provide scope. , attrs.data return string can best way data.
**
<body ng-controller="mainctrl"> <h2>mainctrl</h2> {{data}} <div dir data="data.items"> </div> </body> **
angular.module('app', []) .controller('mainctrl', function($scope) { $scope.data = { items: [{ id: 1, name: "first" }, { id: 2, name: "second" }, { id: 3, name: "third" }] } }) .directive('dir', function() { return { replace: true, restrict: 'a', compile: function(element, attrs) { //need access $scope.data defined in mainctrl. }); } } })
isolate scope pattern bind data parent scope
<div dir data="data.items"> and provide directive's link or controller that
angular.module('app').directive('dir', function() { return { scope: { data: '=' }, ... } }) or can use one-way binding
<div dir data="{{data.items}}"> to in link function attrs.data. that's how angular expects done.
your question describes what's going on during compile phase. can't access scope, ,
<div dir data="{{data.items}}"> won't either because attributes in attrs aren't interpolated in compile function. there reason why doesn't work that: mainctrl runs after directive's compile.
Comments
Post a Comment