javascript - Adding directive scope makes the rest non-updateable -
there's directive called foo
defined this:
<div ng-app="app" ng-controller="maincontroller"> {{ name }} <foo param="123"></foo> </div>
and here's relevant initialization fragment:
var app = angular.module('app', []); app.controller('maincontroller', function($scope){ $scope.name = 'initial name'; }); app.directive('foo', function(){ return { restrict : 'e', controller : function($scope){ $scope.name = 'name defined in directive'; console.log($scope.param); // undefined } }; });
that works expected , overrides initial name
name defined in directive
.
however, since there's param
attribute wanted access value. did 1 way binding this:
return { restrict : 'e', controller : function($scope){ $scope.name = 'name defined in directive'; console.log($scope.param); // 123 expected }, scope : { param : "@" } }
and broke updating of parent scope. when running this, renders initial name
instead of expected name defined in directive
. what's problem here?
when use scope option, create isolate scope definition, separate parent scope.
you either need add name
isolate scope , pass in param
or need remove scope , define param
on parent scope.
here's angular docs have isolate scopes:
as name suggests, isolate scope of directive isolates except models you've explicitly added scope: {} hash object. helpful when building reusable components because prevents component changing model state except models explicitly pass in.
note: normally, scope prototypically inherits parent. isolated scope not. see "directive definition object - scope" section more information isolate scopes.
Comments
Post a Comment