2015-04-23 85 views
1

我已经得到了下面的模板:更新模型值

<select 
    id="someSelect" 
    ng-model="component.picture" 
    ng-controller="someChildController" 
    size="12" 
    ng-options="img.url as img.name for img in image.list | filter:img.filter"> 
</select> 

的重要组成部分,是NG-模型。我想让代码尽可能重用,所以请将此模型视为随时可能更改的模型。问题是,当我无法直接更新$ scope.component.picture时,如何更改控制器的值?

是否有某种方式可以获取元素的模型对象,不管它是什么对象名称?

编辑:

我可能还没有明确。考虑这种情况,在应用程序的不同位置使用相同的模板,但使用改变的模型(因此,没有component.picture)。但它仍然包含在处理模型更新的子控制器中。我无法直接拨打component.picture,因为我无法确定它是ng-model中的一个。

如果一切失败,我可能需要做一些事情,如:

var _el = angular.element('#someSelect'); 
var path = _el.attr('ng-model').split('.'); 
var model = $scope; 
var lastIndex = -1; 

path.forEach(function(p, i) { 
    if(typeof model[p] === 'object') { 
     model = model[p]; 
     lastIndex = i; 
    } 
    else return false; 
}); 

model[path[lastIndex+1]] = "someNewValue"; 

但它很丑陋,所以我想知道,如果有更好的方法来做到这一点。

+0

使用具有特定范围的指令 –

回答

0

使用指令可以注入任何类型的作用域对象,命名空间无关紧要,指令将该数据作为“thisdata”创建一个新的特定作用域,它可以用来显示从提供模板。

// HTML 
<test-dir component="component.picture" images="image.list"></test-dir> 

// JS 
app.directive('testDir', function() { 
    return { 
     restrict: 'E', 
     scope: { component: '=', images: '=' }, 
     template: '<select size="12" ng-options="img.url as img.name for img in images | filter:img.filter"></select>', 
     link: function(scope, elem, attrs) { 
      console.log(scope.component); 
      console.log(scope.images); 
     } 
    } 
}) 

我没有测试它!

+0

是不是在这里隔离的范围?将无法访问image.list数组。而且,它根本不使用** ng-model **。 我想你与源数组混淆模型。 –

+0

您不需要ng模型,您可以在指令中使用隔离范围,您可以在任何地方重复使用。例如,你可以添加另一个像这样的元素:'' - 编辑代码 –

0

你可以使用一个指令,与在那里你传递一个元素列表和模型,如模板:

app.directive("newDirective", function() { 
    return { 
     restrict: 'E', 
     scope: { 
      image: '=', 
      component: '=' 
     }, 
     template: '<select ng-model = "component" size = "12" ng-options = "img.url as img.name for img in image.list | filter:img.filter" > </select>' 

    } 
}); 

这里的HTML存入其应用于每一个指令被称为时间和模板它的创建范围的变量:

  • ngModel
  • 含有的渲染选项列表中的对象

通过这种方式,你可以一个新的模式,每次你需要它:

<new-directive image="img" component="comp.picture"></new-directive> 

哪里img是包含在你的控制器和comp列表中的对象是其中的值存储在变量。

我创建了一个可以帮助你的jsfiddle。

的jsfiddlehttps://jsfiddle.net/vaebkkg9/2/

编辑:我改变了代码,所以你只需要使用component而不是component.picture。如果你想分配一个对象的属性,你只需要使用它作为component="comp.picture"

+0

我想完成的是可重用性。这不包括为指令添加特定的命名空间(这里 - ** component.picture **仍然存在)。 –

+0

希望这可以帮助 – Michael

+0

** component.picture **不存在了 – Michael