javascript - Angularjs undefined object when attribute two-way binding -
i running problem i'm trying in angularjs. thing goes this:
i have controller , have directive defined this:
helpers.directive('someevent', function() { ... scope: { api: '=' } ... controller: ['$scope', function($scope) { $scope.hassomeeventoccured = function(){ return booleanvariable }; $scope.api = { hassomeeventoccured: $scope.hassomeeventoccured } }] });
then, in other controller want access function hassomeeventoccured
... controller defined follows:
modulename.controller('modulesomethingcontroller', ['$scope', '$state', 'modulerepository', function ($scope, $state, modulerepository) { $scope.theeventoccured = $scope.someeventapi.hassomeeventoccured(); }]);
and in cshtml file have:
<some-event api="someeventapi" ></some-event> <div ng-if="theeventoccured"></div>
the error occurs $scope.someeventapi
undefined. , line breaks: $scope.theeventoccured = $scope.someeventapi.hassomeeventoccured();
assume happens because call hassomeeventoccured
within modulesomethingcontroller
occurs before binding someevent
completed.
my question how solve problem?
i aware in directive have like:
link: function(scope, element, attrs) { attrs.$observe(...); }
but how can achieve wait binding complete in situation?
so- reason "$scope.someeventapi undefined" error, because didn't set anywhere. undefined! use inside controller should either defined (var x = something...) or injected (just injected $scope in example)
the way see it, have 2 options want:
- a common , straightforward way define function inside the controller , send function directive. means you'll need add directive definition that:
scope: {theeventoccured: '&' }
the & sign means it's function.
inside controller:
$scope.theeventoccured = function() { /* code here */ }
this way- api defined inside controller, , directive uses when needed.
for more complex stuff- can create .factory , bind controller , directive.
if trying communicate between different controllers (or controllers of directive) can either use factory or $broadcast event. see $broadcast , $emit in the scope api
two other important things: not supposed use directive's function in it's parent controller scope if understand want achieve, not need $observe here.
Comments
Post a Comment