How to set angular controller object property value from directive in child scope

前端 未结 2 1783
南笙
南笙 2020-12-02 11:46

I have have a directive inside an ng-repeater that should set a scope property. Please see the fiddle here: http://jsfiddle.net/paos/CSbRB/

The problem is that the s

相关标签:
2条回答
  • 2020-12-02 12:04

    Not sure what overall objective is but one way is to create 2 attributes, one for the target object and the other for the property of that object:

    <button ng-update1  obj="inputdata" prop="title">
    
    app.directive('ngUpdate1', function() {
        return function(scope, element, attrs) {
            element.bind('click', function() {
                scope.$apply(function() {                
                    scope[ attrs.obj ][attrs.prop] = "Button 1";               
    
                });
            });
        };
    });
    

    DEMO:http://jsfiddle.net/CSbRB/9/

    Alternatively using existing format you could split() value of your current ng-update1 attribute and use result array for object and property in notation

     element.bind('click', function() {
               var target=attrs.ngUpdate1.split('.');
                scope.$apply(function() {                
                    scope[ target[0] ][target[1]] = "Button 1";               
    
                });
            });
    

    DEMO with both approaches: http://jsfiddle.net/CSbRB/10/

    One more approach where you create an isolated scope in directive and can pass in the reference to inputdata object and pull property name from attribute(same markup as second version):

    app.directive('ngUpdate3', function () {
        return {
            scope: {
               targetObject: '=obj'
            },
            link: function (scope, element, attrs) {
                element.bind('click', function () {  
                   scope.$apply(function () {
                        scope.targetObject[attrs.prop]='Button 3';
    
                    });
                });
            }
        }
    });
    

    http://jsfiddle.net/CSbRB/11/

    0 讨论(0)
  • 2020-12-02 12:29

    $parse will solve your problem.

    <button ng-update1="inputdata.title">
    
    app.directive('ngUpdate1', function($parse) {
        return function(scope, element, attrs) {
            var model = $parse(attrs.ngUpdate1);
            console.log(model(scope));  // logs "test"
            element.bind('click', function() {
               model.assign(scope, "Button 1");
               scope.$apply();
            });
        };
    });
    

    Fiddle

    Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to modify the value, use $parse.

    If you don't need to modify the value, you can use $eval instead:

    console.log(scope.$eval(attrs.ngUpdate1));
    
    0 讨论(0)
提交回复
热议问题