javascript - Modifying a model in directive -


a custom directive creates new modified model out of model display purposes using service method.

the problem new model isn't registered @ all.

boo custom attribute model

appreciate kind help.

fiddle

  1. https://jsfiddle.net/u24godsh/
  2. https://jsfiddle.net/u24godsh/1/ using directive controller

template:

<section ng-app="myapp" ng-controller="mycontroller">     <div my-directive boo="model">         <div ng-model="newmodel">             <span>model: </span>  <b>{{model}}</b> <br/>             <span>new model: </span>  <b>{{newmodel || 'undefined'}}</b>         </div>     </div> </section> 

directive

app.directive('boo',['myservice', function (myservice) {     return {         restrict: 'a',         scope: {             boo: '='         },         link: function (scope, element, attrs) {             scope.newmodel = myservice.modifymodel(scope.boo);         }     }; }]).service('myservice', function(){     this.modifymodel = function(model){         var newmodel = [];          for(var key in model) {             newmodel.push(model[key]);         }          return newmodel;     } }); 

controller

var ctrls = angular.module('controllers', []); ctrls.controller('mycontroller', ['$scope', function ($scope) {     $scope.model = {         a: ['a', 'a1'],         b: ['b', 'b1']     }; }]); 

it wont work way because directive uses isolated scope , without template specified directive element content not isolated scope default. couple of easy ways handle setting scope on parent:

   scope.$parent.newmodel = myservice.modifymodel(scope.boo); 

or don't have isolated scope (provided not going use directive multiple times under same scope level), unless make new property name, newmodel, configurable.

return {         restrict: 'a',         link: function (scope, element, attrs) {             var boo = scope.$eval(attrs.boo);             scope.newmodel = myservice.modifymodel(boo);         }     }; 

or same child scope creation.

   return {         restrict: 'a',         scope: true,         link: function (scope, element, attrs) {             var boo = scope.$eval(attrs.boo);             scope.newmodel = myservice.modifymodel(boo);         }     }; 

fiddle


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -