angularjs - How to investigate scope in directive? -
i have plunker show problem: http://plnkr.co/edit/bnha1xornhnyhvxtxsnx?p=preview
angular.module('docstransclusionexample', []) .controller('controller', ['$scope', function($scope) { $scope.arr = [1,2,3,4]; }]) .directive('mydialog', function() { homecoming { restrict: 'e', scope: { arr: '=' }, templateurl: 'my-dialog.html', link: function (scope) { var lengthofarray = scope.arr.length; scope.test = 'the array length ' + lengthofarray; } }; });
in plunker, works like: set scope.arr array, , investigate in link. gives me possibility add together more things scope (test), , print out. using template this:
{{arr}} - {{test}}
.. result:
[1,2,3,4] - array length 4
so: in example, array set on controller straight above. in real implementation of this, array json object, fetched server. result maintain getting 'undefined' result. think might because of (little) delay when directive asks data, until gets delivered, meanwhile link in directive have nil work with.
any ideas can seek out?
update:
i've made plunker show problem:
http://plnkr.co/edit/bnha1xornhnyhvxtxsnx?p=preview
run it, , in result window, should this:
the array length 5 (content of array...)
now then, if go script.js (or other file), , add together linebreak @ bottom or something, plunker reload page. , then, sometimes, script fail read array, , output be:
(content of array...)
i've tried add together watch, not sure if i'm doing correctly.. doesn't seem work.
another funny thing more not, works should on plunker. on localhost, never works.
update 2
i've managed solve using $watch. plunker updated right solution: http://plnkr.co/edit/bnha1xornhnyhvxtxsnx?p=preview
.directive('mydialog', function() { homecoming { restrict: 'e', scope: { contentoflist: '=' }, templateurl: 'my-dialog.html', link: function (scope) { scope.counter = 0; scope.$watch('contentoflist', function() { scope.counter = scope.counter + 1; var lengthofarray = scope.contentoflist.categorylist[0].rows.length; scope.test = 'the array length ' + lengthofarray; }); } }; });
if not define first, nail undefined error, since arr created after making call. did seek creating empty array, , populate it?
something like:
angular.module('docstransclusionexample', []) .controller('controller', ['$scope', '$http', function($scope, $http) { $scope.arr = []; $http.get("somedata.json").success(function(result) { $scope.arr = result; }); }]);
http://plnkr.co/edit/1yt3osdrrbdtpa6fnwt8?p=preview hope helps
angularjs scope directive
No comments:
Post a Comment