Question

I want to use a an expression inside of an NG-MODEL directive Is there a way to accomplish this binding? can it be done using something like compile? here is my markup

<!DOCTYPE html>

<html>
<head>
    <title></title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body ng-controller="AppCtrl">
    <div></div>
    <range min="0" max="100" model="width"></range>
</body>
</html>
<script src="Scripts/angular.min.js"></script>


<script>

var app = angular.module("pager", []);

app.run(function($rootScope){

    console.log($rootScope);    

});

angular.element(document).ready(function(){

    angular.bootstrap(document.querySelector("html"), ["pager"]);

})

app.directive("range", function ($compile) {

    return {

        restrict: "E",
        replace: true,
        scope:{

            min:"@",
            max:"@",
            model:"@"

        },
        template: "<input type='range' ng-model='{{model}}' value='0' min='{{min}}' max='{{max}}'/>",

    }

})
</script>

ng-model='{{model}}' gives you an error is there a way to get it read the model attribute from the directive? Is that possible to link it that way or do i have to use $compile to accomplish this. I want my directives to be able to create variables in the child scope then bind it to the ng-model that the directive is generating. I want to use the attribute of "model" from the directive to create the variable for the ng-model. in this example I want "width" to be where the {{model}} expression is.

Was it helpful?

Solution

Is this what you are looking for?

If you replace the @ with the = than you will see it on your controller $scope (without using an expression), take a look at the below code and fiddle.

Edit

app.directive("range", function ($compile) {
    return {
        restrict: "E",
        replace: true,
        scope: {
            min: "@",
            max: "@",
            model: '='
        },
        compile: function () {
            return {
                pre: function (scope, elem, attrs) {
                    // The directives isolated scope
                    console.log(scope);
                    // Controller scope
                    console.log(scope.$parent);
                }
            }
        },
        template: "<input type='range' ng-model='model' value='0' min='{{min}}' max='{{max}}'/>"
    }
});

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top