1

I am a starter in angular js.

I went through similar question How to access parent scope from within a custom directive *with own scope* in AngularJS?

But the answer did not worked for my simple experiment.

here is the sandbox. http://jsfiddle.net/VJ94U/1364/

angular.module('mod', []).
directive('myBind', function() {
  return {
    restrict : 'A',
    scope : {
      scopeVar : '@'
    },
    link : function(scope,element,attr){
      element.attr('ng-bind', scope.scopeVar);
      element.text(scope.scopeVar);
    }
  };
});


var app = angular.module('app', [ 'mod' ]);
angular.element(document).ready(function() {
  angular.module('app').run(function($rootScope){
    $rootScope.scopeVar = 'This is scope variable.';
  });
  angular.bootstrap(document, ['app']);
});

I simply want my own my-bind (as replica of ng-bind)

so value of attribute my-bind is a name of some scopeVariable and whenever that scope variable value changes, the content of div should get updated with that updated value.

Neither i got the parent scope variable value nor the element get the respective text.

PS : i know i should have used = but i just starting with @ at least check to find scope variable and use it value. PS : i also want to avoid using $parent

Community
  • 1
  • 1
codeofnode
  • 18,169
  • 29
  • 85
  • 142
  • good to have the first solution but main and second problem binding did not worked http://jsfiddle.net/VJ94U/1366/ – codeofnode Oct 06 '15 at 15:25

1 Answers1

1

You can implement your custom ng-bind as a simple directive, like this one:

<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="scopeVar"><br>
  <div my-bind data="scopeVar"></div>
</div>

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.scopeVar = "Bind me";
  }])
  .directive("myBind", function(){
    return {
      template: "<p ng-bind='myVar'></p>",
      scope: {
        myVar: "=data",
      }
    }
  });
ZenDD
  • 906
  • 1
  • 7
  • 16
  • nice one but my directive also have various other attributes that i do not want to put into template again and again. – codeofnode Oct 06 '15 at 16:10
  • i could not find the 2 way binding as in ng-bind binding.. see setTimeout here http://jsfiddle.net/VJ94U/1367/ – codeofnode Oct 07 '15 at 09:56
  • also what it seems answer does not link to question well. I just want a replica of ng-bind. Like content of div should be updated whenever my-bind scope variable value changes – codeofnode Oct 07 '15 at 10:00
  • you said you needed multiple attributes, so that was one of the ways you could reach them. However for two-way-binding the 1st example should work quite fine (and though it was fairly obvious, i've added the input element which you can use to update the value). As a matter of fact nothing is stopping you from adding extra attributes to the directive, it only depends on how you intend to use them.. – ZenDD Oct 07 '15 at 10:24